简体   繁体   English

为什么这个 Javascript 函数总是返回 true?

[英]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 .我构建了一个函数every应该遍历一个数组并返回true如果对所有元素执行的操作(例如 element < 10)为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?使用array1 ,即使它包含大于 10 的数字,它也会返回true 。问题出在哪里?

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您需要评估 trueOrFalse 是否等于 true 对于您需要双重等于

if (trueOrFalse == true) return true;

Other wise you'll just be making the value of trueOrFalse the same as true否则,您只会使 trueOrFalse 的值与 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;您可以使用if (trueOrFalse == true) return true;

OR或者

you can write it as if (trueOrFalse) return true;你可以把它写成if (trueOrFalse) return true; which will still evaluate it as if( true )它仍然会像if( true )一样评估它

You can remove the if statement and rely on good old boolean algebra!您可以删除if语句并依靠良好的旧布尔代数!

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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