给定以下数组:
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 v 7.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));
这样的代码总能按预期找到元素。
我不明白为什么只使用 find
和 includes
的两个调用会产生不同的结果,如果有人知道解释,我会很高兴。
最佳答案
x.find(y.includes, y);
返回 undefined
的原因是函数中传递了参数。
Array.find
的回调需要 3 个值,即 item, index, array
和 Array.includes
的回调需要 2 个参数,即,item,fromIndex
。
基本上,您当前的索引将被视为 Array.includes
中的 fromIndex
并将跳过它之前的元素。
因此,在四次迭代之后,Array.includes
将在第 4 个元素之后查找值,而 y
没有这些值。因此它返回 undefined
。
关于javascript - 数组混淆与查找和包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328502/