简体   繁体   中英

Can someone help me interpret the if statement in this javascript code?

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (callback(array[i])) newArray.push(array[i]);
  }
  return newArray;
}

I'm confused by the syntax. Typically what I've seen so far is

if (condition) {
  // code to be executed
}

where condition is some boolean statement which will run the code shown if condition = true.

But, in this if statement, there is no boolean, nor is there code to be executed after the conditonal statement. I have no clue what it means. Thanks in advance for any help interpeting it.

(callback(array[i])) this part is the condition. newArray.push(array[i]) this is what happens when the condition is met. It just looks so close together.

 if (callback(array[i])) { newArray.push(array[i]) }

Does same thing.

There is a boolean, namely the value returned from calling the function callback with argument array[i] . (To be precise: The interpretation of the returned value as a truth value according to the JavaScript language specs - this is what is meant by 'truthy' or 'falsy'. For starters just assume that callback does indeed return a boolean value)

There also is code being executed: The first statement after the condition. This is just a notational shorthand. The verbose equivalent code would be:

if (callback(array[i])) {
    newArray.push(array[i]);
}

if (callback(array[i])) newArray.push(array[i]); simply means that callback is a function, that gets called and a return value is expected (could be any value, not only boolean). Then, if the return is truthy , the statement newArray.push(array[i]); gets executed.

(A single line if (exp) statement; can be written like this, but may sometimes hide bugs, so some linters prefer to always change it to

if (exp) {
  statement;
}

Callbacks are typically functions that get passed in as an argument (exactly as you see here) that then may get called.

If your condition isn't working try to use a if else loop. If your statement isn't what you expect show an error message, else push array[i];

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (!callback(array[i])){
       console.log('Something went wrong');
  }else{
       newArray.push(array[i]);
    }
  return newArray;
}
´´´

Since you only give this piece of code, it's hard to analyze it, but this may work

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