【问题标题】:Array confusion with find and includes数组与查找和包含混淆
【发布时间】:2017-11-03 20:09:28
【问题描述】:

给定以下数组:

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)); 这样的代码总是能按预期找到元素。

我不明白为什么只使用 findincludes 的两个调用会产生不同的结果,如果有人知道解释会很高兴。

【问题讨论】:

  • find() 和 includes() 的参数不同。

标签: javascript arrays ecmascript-6


【解决方案1】:

x.find(y.includes, y); 返回undefined 的原因是函数中传递了参数。

Array.find 的回调需要 3 个值,即 item, index, arrayArray.includes 的回调需要 2 个参数,即 item, fromIndex

基本上,您当前的索引将在Array.includes 中被视为fromIndex,并会跳过它之前的元素。

因此,经过四次迭代后,Array.includes 将查找第 4 个元素之后的值,而y 没有它们。因此它返回undefined

【讨论】:

  • 哇。这对我来说很微妙。感谢您的澄清!
猜你喜欢
  • 2011-01-29
  • 2017-09-24
  • 2023-03-29
  • 2017-12-05
  • 2018-08-25
  • 2021-03-24
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多