Jak*_*nge 9 javascript arrays ecmascript-6
给定以下数组:
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];
Run Code Online (Sandbox Code Playgroud)
使用节点v 7.3.0我观察到以下意外行为:
[> x.find(y.includes, y);
undefined
[> y.find(x.includes, x);
682
Run Code Online (Sandbox Code Playgroud)
示例代码段:
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))Run Code Online (Sandbox Code Playgroud)
但是,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.
基本上,您当前的索引将被视为fromIndexin Array.includes并将跳过之前的元素.
因此,在四次迭代看起来之后,Array.includes将在第四个元素之后查找值并且y没有它们.因此它返回undefined.