使用find和includes时的数组混淆问题

9

给定以下数组:

const x = [2, 14, 54, 109, 129, 136, 165, 312, 320, 330, 335, 348, 399, 440, 450, 461, 482, 501, 546, 547, 549, 559, 582, 584, 615, 620, 647, 682];
const y = [539, 681, 682, 683];

使用 Node v7.3.0,我观察到以下意外行为:

[> x.find(y.includes, y);
undefined
[> y.find(x.includes, x);
682

示例代码段:

const x = [2, 14, 54, 109, 129, 136, 165, 312, 320, 330, 335, 348, 399, 440, 450, 461, 482, 501, 546, 547, 549, 559, 582, 584, 615, 620, 647, 682];
const y = [539, 681, 682, 683];

console.log(x.find(y.includes, y))
console.log(y.find(x.includes, x))

然而像 x.find(element => y.includes(element)); 这样的代码总是能按预期找到元素。
我不明白为什么只使用 findincludes 两个调用会产生不同的结果,如果有人知道解释,我会很高兴的。

3
find() 和 includes() 方法的参数是不同的。 - charlietfl
1个回答

5
x.find(y.includes, y); 返回 undefined 的原因是函数传入的参数不正确。 Array.find 的回调函数需要三个值,即 item, index, array,而 Array.includes 的回调函数需要两个参数,即 item, fromIndex
基本上,当前的索引将被视为 Array.includes 中的 fromIndex,并且会跳过它之前的元素。
因此,在四次迭代后,Array.includes 将查找第 4 个元素之后的值,但 y 没有这些值。因此返回 undefined

哇,这对我来说很微妙。感谢您的澄清! - Jakob Runge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接