Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array.prototype.includes #7

Open
chenxiaochun opened this issue Sep 17, 2017 · 0 comments
Open

Array.prototype.includes #7

chenxiaochun opened this issue Sep 17, 2017 · 0 comments

Comments

@chenxiaochun
Copy link
Owner

chenxiaochun commented Sep 17, 2017

通过单词意思也能看出来,此方法用来判断元素是否存在于一个数组中,存在返回true,否则返回false

['a', 'b', 'c'].includes('a')
true
['a', 'b', 'c'].includes('d')
false

includes非常类似的一个方法是indexOf,比如下面两种用法实现的作用是一样的。

arr.includes(x)
arr.indexOf(x) >= 0

includes方法还可以查找NaN

[NaN].includes(NaN)
true

indexOf方法却不行。

[NaN].indexOf(NaN)
-1

includes方法不能区分+0-0

[-0].includes(+0)
true

类型化数组中也同样存在一个includes方法。

let tarr = Uint8Array.of(12, 5, 3);
console.log(tarr.includes(5));
true

FAQ

  • 为什么此方法会被命名为includes,而不是contains

contains确实是最初的选择,但是后来某些代码库(MooTools)有了同名的实现,就被放弃了。

  • 接上一问题,为什么它也没有被命名为has呢?

因为has方法用于判断键值对(Map.prototype.has),而includes通常用于判断元素(String.prototype.includes)。一个集合(Set)的所有元素是可以通过keyvalue分别查看的,这也是为什么Set中也没有includes方法了。

  • String.prototype.includes方法的工作机制是基于字符串,而不是基于字符的。可这是不是就和Array.prototype.includes方法的工作机制不一致了?如果数组的includes方法和String上的保持一致,那么数组的includes方法参数接受的应该是一个数组,而不能是一个单一元素。但是,这两个对象上的includes方法又是模仿的indexOf方法。字符是一种特定情况,字符串一般情况下都是拥有一定的长度。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant