简体   繁体   中英

Use an array as an argument in a function

I am a bit new into programming and I have this function:

function filterJSON(json, key, value) {
  var result = [];
  json.forEach(function(val,idx,arr){
    if(val[key] == value){

      result.push(val)
    }
  })

My problem is the understanding of the second part:

json.forEach(function(val,idx,arr){
    if(val[key] == value){

      result.push(val)
    }
  })

We got in this case val as an argument and in the if statement we use the term val[key] . So does this means, the argument val is an array? And at the end, we push a whole array into the empty array named result ?

Thanks a lot!

Let's break this down:

json.forEach(function(val,idx,arr){

forEach takes a function. The first argument is one of the values from the thing being iterated over. The second and third arguments are the current index and the array itself, which you need if you want to mess around with the array while iterating through it.

In this case, the function will receive each of the things stored in the json object, one at a time.

if(val[key] == value){

val is an object. val[key] means "from val , get the property named key ".

result.push(val)

If val 's key property was equal to the value we're filtering for, we push the val object into the list of things that gets returned.

I think the point of confusion is in the meaning of val[key] . The [] syntax is used both to index into an array ( arr[0] gets the first thing in a list ) and to get a property of an object ( foo[bar] gets foo.bar )

Yes, val should be an array because forEach() is an array method.

The forEach() method calls a provided function once for each element in an array, in order.

No, push() doesn't mean that the whole array will be pushed into result , but only the value inside the parentheses () .

The push() method adds new items to the end of an array, and returns the new length.

Note: also remember to use === instead of == in JavaScript which was described here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM