简体   繁体   中英

Why does this Javascript function always return true?

I built a function every that should iterate over an array and return true if the action (for ex. element < 10) performed on all the elements is true . Here's my code:

function every(array, action) {
  var trueOrFalse = true
  for (var i = 0; i < array.length; i++)  
    trueOrFalse = trueOrFalse && action(array[i]);
  if (trueOrFalse = true) return true;
  else  return;
}
array1 = [1,2,3,4,5,6,7,8,9,10,11]
console.log(every(array1, function(element) {
  return element < 10 
}))

I don't see anything wrong. With array1 it returns true even if it contains numbers > 10. Where's the problem?

Thanks

if (trueOrFalse = true) return true; 

应该

if (trueOrFalse == true) return true;

You need to evaluate trueOrFalse is equal to true For which you need the double equals

if (trueOrFalse == true) return true;

Other wise you'll just be making the value of trueOrFalse the same as true

Bonus points:

 if (trueOrFalse === true) return true;

Using three equal signs is evaluating exactly the same type and value. That isn't required here but is useful to know.

Your condition is using an incorrect operator, you should be using the == operator.

You can use if (trueOrFalse == true) return true;

OR

you can write it as if (trueOrFalse) return true; which will still evaluate it as if( true )

You can remove the if statement and rely on good old boolean algebra!

function every(array, action) {
  var trueOrFalse = true
  for (var i = 0; i < array.length; i++)  
    trueOrFalse = trueOrFalse && action(array[i]);
  return trueOrFalse;
}
array1 = [1,2,3,4,5,6,7,8,9,10,11]
console.log(every(array1, el => el < 10));

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