为什么这个.every()函数返回true然后返回false?

时间:2018-03-19 03:11:38

标签: javascript arrays iterator

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

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

=&GT;假

当我在https://repl.it/@super8989/BraveFunctionalSale中运行此代码时,会返回&#34; true&#34;然后&#34; =&gt;假&#34 ;.

根据.every()描述,如果回调函数为每个数组元素返回一个truthy值,则返回值为&#34; true;否则,假。&#34;

为什么会显示&#34; true&#34;然后&#34; =&gt;假&#34;吗

此外,当我更改数组时,&#34; - value&#34;在数组的中间,它返回&#34; false&#34;然后&#34; =&gt;假&#34;

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

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

=&GT;假

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

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

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

=&GT;未定义

但是如果我这样写,那么返回false然后是undefined。 https://repl.it/@super8989/MonstrousAjarDimension

我很困惑......请帮忙!

2 个答案:

答案 0 :(得分:0)

你需要在.every中使用return,目前你只是记录num&lt; 0对于num [0]是真的,它是(-1 <0),但对于num [1]是假的,它是(50> = 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)));

答案 1 :(得分:0)

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

为每个元素返回undefined(缺少return语句)。

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

或在es-2017语法中:

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