Array.prototype.includes与Array.prototype.indexOf [英] Array.prototype.includes vs. Array.prototype.indexOf

查看:120
本文介绍了Array.prototype.includes与Array.prototype.indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了提高可读性之外,还包括还有 indexOf 的优势吗?它们看起来和我一模一样。

Beyond the improved readability, is there any advantage to includes over indexOf? They seem identical to me.

这个

var x = [1,2,3].indexOf(1) > -1; //true

这个?

var y = [1,2,3].includes(1); //true


推荐答案

tl; dr: NaN 的处理方式不同:


  • [ NaN] .indexOf(NaN)> -1 false

  • [NaN] .includes(NaN) true

  • [NaN].indexOf(NaN) > -1 is false
  • [NaN].includes(NaN) is true

来自提案


动机



使用ECMAScript数组时,通常需要确定数组是否包含元素。现行的模式是

Motivation

When using ECMAScript arrays, it is commonly desired to determine if the array includes an element. The prevailing pattern for this is

if (arr.indexOf(el) !== -1) {
    ...
}

以及其他各种可能性,例如 arr.indexOf(el)> = 0 ,甚至 ~arr.indexOf(el)

with various other possibilities, e.g. arr.indexOf(el) >= 0, or even ~arr.indexOf(el).

这些模式存在两个问题:

These patterns exhibit two problems:


  • 他们未能说出你的意思:你不知道数组是否包含一个元素,而是询问数组中第一次出现该元素的索引是什么,然后比较它或者用它来旋转它,以确定你实际问题的答案。

  • 它们因 NaN 而失败,因为 indexOf 使用Strict Equality Comparison,因此 [NaN] .indexOf(NaN)=== -1

  • They fail to "say what you mean": instead of asking about whether the array includes an element, you ask what the index of the first occurrence of that element in the array is, and then compare it or bit-twiddle it, to determine the answer to your actual question.
  • They fail for NaN, as indexOf uses Strict Equality Comparison and thus [NaN].indexOf(NaN) === -1.

我们建议添加 Array.prototype.includes 方法,以便上述模式可以重写为

We propose the addition of an Array.prototype.includes method, such that the above patterns can be rewritten as

if (arr.includes(el)) {
    ...
}

除了使用SameValueZero比较之外,它具有与上述几乎相同的语义。算法而不是严格的等式比较,从而使 [NaN] .includes(NaN)为真。

This has almost the same semantics as the above, except that it uses the SameValueZero comparison algorithm instead of Strict Equality Comparison, thus making [NaN].includes(NaN) true.

因此,这提案解决了现有代码中出现的两个问题。

Thus, this proposal solves both problems seen in existing code.

我们另外添加一个 fromIndex 参数,类似于 Array.prototype.indexOf String.prototype.includes ,为了保持一致。

We additionally add a fromIndex parameter, similar to Array.prototype.indexOf and String.prototype.includes, for consistency.






更多信息:


Further information:

  • SameValueZero algorithm
  • Strict Equality Comparison algorithm

这篇关于Array.prototype.includes与Array.prototype.indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆