New to Javascript, still confused about parameter
Here are some codes:
var people = [{
name: 'Casey',
rate: 60
},
{
name: 'Camille',
rate: 80
},
{
name: 'Gordon',
rate: 75
},
{
name: 'Nigel',
rate: 120
}
];
function priceRange(person) {
return (person.rate >= 65) && (person.rate <= 90);
};
var results = [];
results = people.filter(priceRange);
I know this is a very basic question, but I just want to know the parameter "person".How did the computer know the parameter "person" is coming from the object "people"?
-
Does the Array#filter documentation help you understand?Jaromanda X– Jaromanda X2017年01月23日 03:14:07 +00:00Commented Jan 23, 2017 at 3:14
2 Answers 2
Data structures :
[....]this is an array{attr1:'val1', attr2: 'val2',. ...}this is a literal object.
👉🏼 ↪ people is an ARRAY of literal objects , and each object has two attributes (keys) : name & rate.
Functional Programming:
Since people is an array, Array class provides a set of methods ,namely filter() which accepts as first argument : FUNCTION .
filter() will run the function (1st argument of filter) for each item , then if it returns true, it accepts the element , and vice versa .
Let's take , an example more simple than what you have : let's take an Array of digits
const arrayOfDigits = [23, 400 , 99, 4, 222];
function exceed100(element) {
return element > 100;
}
console.log(
arrayOfDigits.filter(exceed100)
)
example above filters all digits less or equal to 100.and it keep only digits exceeds 100.
2 Comments
person, element, ...item, however you should keep the order (person is the 1st arg, index is the 2nd arg.. so on)The Array.prototype.filter() function loops through the array that it was called on, and calls the callback function with each element as an argument. So when you use people.filter(priceRange), the filter() function calls priceRange with each element of people. The code of filter() is something like this (I've simplified it greatly just to show how this part works):
function filter(callback) {
var result = [];
for (var i = 0; i < this.length; i++) {
if (callback(this[i])) {
result.push(this[i]); // This gets person from people
}
}
return result;
}