背景
我正在编写一些代码来检查 2 个数组是否相同,但出于某种原因,结果在预期为 false 时为 true。仔细检查后,我发现未定义的数组值被跳过了。
例子
const arr1 = [, , 3, 4]
const arr2 = [1, 2, 3, 4]
const result = arr1.every((item, index) => item === arr2[index])
console.log(result) // true (HOW????)
我尝试过的
所以我花了一些时间试图正确地获取此处的值,但我唯一想出的是一个常规的 for 循环,它根据数组长度而不是实际项目进行迭代。
问题
为什么会发生这种情况,有没有办法识别我的数组中的这些空值/未定义值?
最佳答案
这是 forEach
仅访问实际存在的元素这一事实的扩展。除了为丢失的元素调用回调没有多大意义之外,我不知道还有更深层次的“原因”。
您可以通过使用以下方式实现这些元素(如果那是世界的话):
- 扩展符号,或
Array.from
,或者Array.prototype.values
,或者Array.prototype.entries
...或者可能还有其他一些。
const a = [, , 3];
console.log(a.hasOwnProperty(0)); // false
const b = [...a];
console.log(b.hasOwnProperty(0)); // true
const c = Array.from(a);
console.log(b.hasOwnProperty(0)); // true
使用 Array.from
将其应用于您的函数:
const arr1 = [, , 3, 4]
const arr2 = [1, 2, 3, 4]
const result = Array.from(arr1).every((item, index) => item === arr2[index])
console.log(result) // false
当然,这涉及创建一个新数组并循环遍历前一个数组以复制元素。使用自己的 for
循环可能会更好。
将 Array.prototype.entries
应用于您的函数:
const arr1 = [, , 3, 4]
const arr2 = [1, 2, 3, 4]
let result = true;
for (const [index, value] of arr1.entries()) {
if (value !== arr2[index]) {
result = false;
break;
}
}
console.log(result) // false
关于javascript - 为什么 map、every 和其他数组函数会跳过空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57394690/