【问题标题】:Why does this .every() function return true and then false?为什么这个 .every() 函数返回 true 然后返回 false?
【发布时间】:2018-08-27 13:24:09
【问题描述】:
let nums = [-1, 50, 75, 200, 350, 525, 1000];

nums.every(function(num) {
  console.log(num < 0);
});

=> 错误


当我在https://repl.it/@super8989/BraveFunctionalSale 中运行此代码时,它会返回“true”然后“=> false”。

根据.every()的描述,返回值为“如果回调函数为每个数组元素返回一个真值,则返回值为真;否则为假。”

为什么显示“true”,然后显示“=> false”?


此外,当我更改数组以使“- value”位于数组中间时,它会返回“false”,然后返回“=> false”。

let nums = [1, 50, -75, 200, 350, 525, 1000];

nums.every(function(num) {
  console.log(num < 0);
});

=> 错误

https://repl.it/@super8989/CyberInterestingPhase


let nums = [-1, 50, 75, 200, 350, 525, 1000];

console.log(nums.every(num => num < 0));

=> 未定义

但是如果我这样写,这将返回 false 然后未定义。 https://repl.it/@super8989/MonstrousAjarDimension


我很困惑...请帮忙!

【问题讨论】:

    标签: javascript arrays iterator


    【解决方案1】:

    您需要在 .every 中使用 return,目前您只记录 num = 0)。并且由于您不return 立即退出循环,因为这被认为是false

    let numsA = [-1, 50, 75, 200, 350, 525, 1000];
    console.log("should return false, because 50 is >= 0");
    console.log(numsA.every(function(num) {
      return (num < 0);
    }));
    
    let numsB = [1, 50, -75, 200, 350, 525, 1000];
    
    console.log(numsB.every(function(num) {
      return (num < 0);
    }));
    
    let numsC = [-1, 50, 75, 200, 350, 525, 1000];
    
    console.log(numsC.every(num => num < 0));
    
    let numsD = [-5, 0, 5, 10, 15];
    console.log("should return true because for each num in numsD, num %5 === 0");
    console.log(numsD.every(num => {
      return num % 5 === 0
    }));
    //you can omit return with arrow function syntax, as this automatically returns the value within ()
    console.log(numsD.every(num => (num % 5 === 0)));

    【讨论】:

      【解决方案2】:

      在 Array.every 方法中,您必须提供 返回 true 或 false 的函数。 Array 中的每个元素都调用函数。 https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/every

      你的功能

      nums.every(function(num) {
        console.log(num < 0);
      });
      

      为每个元素返回未定义(缺少返回语句)。

      var resutl = nums.every(function(num) {
        return (num < 0);
      });
      

      或在 es-2017 语法中:

      const resutl = nums.every(num => num < 0);
      

      【讨论】:

        猜你喜欢
        • 2018-11-09
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        • 2013-09-18
        • 2015-06-22
        • 2015-06-21
        • 2021-04-22
        • 2021-11-10
        相关资源
        最近更新 更多