这是一些 Javascript 数组方法的常见问题。以下面为例:
var numbers = new Array(12, 5, 8, 130, 44);
function isBigEnough(element, index, array) {
return element >= 10;
}
alert(numbers.every(isBigEnough));
这将返回 FALSE。 当我第一次阅读这些迭代数组的方法(例如 every、some、filter、forEach、map)时,我认为将为每个元素调用函数 isBigEnough。因此,在上面的示例中,我本以为 isBigEnough 会被单独调用 5 次,并有 5 个返回值。显然情况并非如此。
我现在猜测该方法调用了该函数 5 次,但 Return 实际上不会返回任何内容,直到所有元素都为 TRUE 或找到 FALSE 为止。
有人知道显示这些迭代方法的过程或流程的流程图或图形吗?
谢谢
最佳答案
这些方法的 Mozilla 文档非常好。对于 every
和 some
它特别指出,这些方法在找到假值/真值时立即返回。
every
The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
some
some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returns true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
关于javascript - every() 和其他迭代方法有多少个 Returns?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572873/