Javascript Array.prototype.includes 与 Array.prototype.indexOf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35370222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:39:01  来源:igfitidea点击:

Array.prototype.includes vs. Array.prototype.indexOf

javascriptecmascript-7

提问by Matt

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

除了提高可读性之外,includesover有什么优势indexOf吗?他们对我来说似乎相同。

What is the difference between this

这有什么区别

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

And this?

和这个?

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

回答by Felix Kling

tl;dr:NaNis treated differently:

tl;dr:NaN区别对待:

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


From the proposal:

提案

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) {
    ...
}

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

These patterns exhibit two problems:

  • 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 indexOfuses Strict Equality Comparison and thus [NaN].indexOf(NaN) === -1.

Proposed Solution

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

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

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.

We additionally add a fromIndexparameter, similar to Array.prototype.indexOfand String.prototype.includes, for consistency.

动机

使用 ECMAScript 数组时,通常需要确定数组是否包含元素。这方面的普遍模式是

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

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

这些模式存在两个问题:

  • 他们没有“说出你的意思”:不是询问数组是否包含一个元素,而是询问该元素在数组中第一次出现的索引是什么,然后比较它或对其进行位旋转,以确定您实际问题的答案。
  • 他们失败了NaN,因为indexOf使用了严格相等比较,因此[NaN].indexOf(NaN) === -1.

建议的解决方案

我们建议增加一个Array.prototype.includes方法,这样上面的模式就可以改写为

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

这与上面的语义几乎相同,除了它使用 SameValueZero 比较算法而不是 Strict Equality Comparison ,从而使[NaN].includes(NaN)true 。

因此,该提议解决了在现有代码中看到的两个问题。

为了一致性fromIndex,我们还添加了一个类似于Array.prototype.indexOf和的参数String.prototype.includes



Further information:

更多信息:

回答by 538ROMEO

If you wonder about performances, for the moment, indexOf is faster, but this JSperftest tend to show that more the time pass, more includes()will be faster than indexOf(i guess it will be optimized further).

如果您想知道性能,目前 indexOf 更快,但是这个JSperf测试往往表明时间越长,includes()越快indexOf(我猜它会进一步优化)。

IMHO, i also prefer to write if (arr.includes(el)) {}since it is clearer and more maintainable than if (arr.indexOf(el) !== -1) {}

恕我直言,我也更喜欢写,if (arr.includes(el)) {}因为它比if (arr.indexOf(el) !== -1) {}

回答by Srishti

.indexOf()and .includes()methods can be used to search for an element in an array or to search for a character/substring in a given string.

.indexOf()and.includes()方法可用于搜索数组中的元素或搜索给定字符串中的字符/子字符串。

Usage in Array

数组中的用法

(Linkto ECMAScript Specification)

链接到 ECMAScript 规范)

  1. indexOfuses Strict Equality Comparisonwhereas includesuses the SameValueZeroalgorithm. Because of this reason, the following two points of differences arise.

  2. As pointed out by Felix Kling, the behavior is different in case of NaN.

  1. indexOf使用严格相等比较includes使用SameValueZero算法。由于这个原因,出现了以下两点差异。

  2. 正如Felix Kling所指出的,在 的情况下,行为是不同的NaN

let arr = [NaN];

arr.indexOf(NaN); // returns -1; meaning NaN is not present
arr.includes(NaN); // returns true
  1. The behavior is also different in case of undefined.
  1. 在 的情况下,行为也不同undefined
let arr = [ , , ];

arr.indexOf(undefined); // returns -1; meaning undefined is not present
arr.includes(undefined); // returns true

Usage in String

字符串中的用法

(Linkto ECMAScript Specification)

链接到 ECMAScript 规范)

  1. If you pass a RegExp to indexOf, it will treat the RegExp as a string and will return the index of the string, if found. However, if you pass a RegExp to includes, it will throw an exception.
  1. 如果您将 RegExp 传递给indexOf,它会将 RegExp 视为字符串并返回字符串的索引(如果找到)。但是,如果您将 RegExp 传递给includes,它将引发异常。
let str = "javascript";

str.indexOf(/\w/); // returns -1 even though the elements match the regex because /\w/ is treated as string
str.includes(/\w/); // throws TypeError: First argument to String.prototype.includes must not be a regular expression

Performance

表现

As 538ROMEOpointed out, includesmay be a little (very tiny) bit slower (for it needs to check for a regex as the first argument) than indexOfbut in reality, this doesn't make much difference and is negligible.

正如538ROMEO指出的那样,includes可能比(因为它需要检查正则表达式作为第一个参数)慢一点(非常小),indexOf但实际上,这没有太大区别,可以忽略不计。

History

历史

String.prototype.includes()was introduced in ECMAScript 2015 whereas Array.prototype.includes()was introduced in ECMAScript 2016. With regards to browser support, use them wisely.

String.prototype.includes()是在 ECMAScript 2015Array.prototype.includes()中引入的,而在 ECMAScript 2016 中引入。关于浏览器支持,请明智地使用它们。

String.prototype.indexOf()and Array.prototype.indexOf()are present in ES5 edition of ECMAScript and hence supported by all browsers.

String.prototype.indexOf()并且Array.prototype.indexOf()出现在 ECMAScript 的 ES5 版本中,因此被所有浏览器支持。

回答by Sebastian Gomez

Conceptually you should use indexOf when you want to use the position indexOf just give you to extract the value or operate over the array, i.e using slice, shift or split after you got the position of the element. On the other hand, Use Array.includes only to know if the value is inside the array and not the position because you don't care about it.

从概念上讲,当您想使用 indexOf 位置时,您应该使用 indexOf 只是让您提取值或对数组进行操作,即在获得元素位置后使用切片、移位或拆分。另一方面,使用 Array.includes 只知道值是否在数组内而不是位置,因为您不关心它。

回答by Kruti

indexOf()and includes()can both be used to find elements in an array, however each function yields different return values.

indexOf()includes()都可以用于查找数组中的元素,但是每个函数产生不同的返回值。

indexOfreturns a number (-1if element not present in the array, or array position if the element is present).

indexOf返回一个数字(-1如果元素不存在于数组中,或者如果元素存在则返回数组位置)。

includes()returns a boolean value (trueor false).

includes()返回一个布尔值(truefalse)。