简体   繁体   English

Array.prototype.every 在测试数组中的空值有长度时返回 true?

[英]Array.prototype.every return true when testing empty value in an array has length?

I am trying to check is every element is array has truthy value.我试图检查是否每个元素都是数组具有真实值。

But I am confused when testing an array has some empty value.但是当测试一个数组有一些空值时我很困惑。

var arr = [];
arr[10] = 1;
arr; // [empty x 10, 1];
arr.every(item => Boolean(item)); // true ???
Boolean(arr[0]); // false ???!!!

this is what I get when running the code above on chrome devtool console这是我在 chrome devtool 控制台上运行上面的代码时得到的在此处输入图像描述

every , some , map , filter , and most of the others only visit array entries that exist, they don't visit the gaps in sparse arrays like yours. everysomemapfilter和其他大多数只访问存在的数组条目,它们不会像你一样访问稀疏 arrays 中的间隙。 So the result is only based on checking the values of elements that actually exist.因此结果仅基于检查实际存在的元素的值。

You can see that if you step through the callback or add logging to it:您可以看到,如果您单步执行回调或向其中添加日志记录:

 var arr = []; arr[10] = 1; arr.every((item, index) => { console.log(`Visited index ${index}, item = ${item}`); return Boolean(item); }); // => // Visited index 10, item = 1 // Note that 0-9 are gaps: console.log(`0 in arr? ${0 in arr}`); // false console.log(`9 in arr? ${9 in arr}`); // false console.log(`10 in arr? ${10 in arr}`); // true

As you can see, the every callback in that only outputs one line because it's only called once.如您所见,其中的every回调只输出一行,因为它只被调用一次。

If you want that array to actually have undefined for elements 0 through 9, you could use fill ;如果您希望该数组实际上undefined元素 0 到 9,则可以使用fill then every would test element 0 and return false since Boolean(undefined) is false :然后every将测试元素 0 并返回false ,因为Boolean(undefined)false

 var index = 10; var arr = Array(index + 1).fill(); arr[index] = 1; console.log(arr.every(Boolean)); // false

Most array operations don't operate on unassigned indexes in sparse arrays.大多数数组操作不对稀疏 arrays 中的未分配索引进行操作。 From the MDN documentation :MDN 文档

callback is invoked only for array indexes which have assigned values. callback仅针对已分配值的数组索引调用。 It is not invoked for indexes which have been deleted, or which have never been assigned values.对于已被删除或从未被赋值的索引,它不会被调用。

You only have one index with an assigned value which is truthy, so your call to every() will return true.您只有一个分配了真实值的索引,因此您对every()的调用将返回true。

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

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