Reputation: 53
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"?
Upvotes: 1
Views: 36
Reputation: 93173
[....]
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.
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 (1ˢᵗ 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.
Upvotes: 1
Reputation: 780724
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;
}
Upvotes: 0