本文为 《JavaScript 新书:探索 ES2016 与 ES2017》的内容章节,你可以点击链接查看完整目录。
本章介绍由 Domenic Denicola 和 Rick Waldron 提议的 ECMAScript 2016 新特性 Array.prototype.includes
。
概述
> ['a', 'b', 'c'].includes('a') true > ['a', 'b', 'c'].includes('d') false
数组方法 includes
数组方法 includes
有以下签名:
Array.prototype.includes(value : any) : boolean
如果某个数组中包含 value
这个元素,则返回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
,而 indexOf()
不能:
> [NaN].includes(NaN) true > [NaN].indexOf(NaN) -1
includes
不区分 +0
和 -0
( ):
> [-0].includes(+0) true
TypedArray 同样有 includes()
方法:
let tarr = Uint8Array.of(12, 5, 3); console.log(tarr.includes(5)); // true
常见问题
- 为什么这个方法叫做
includes
而不是contains
?
后者(即:contains
)是最初的选择,但是这将破坏了网上现有的代码( 例如:)。 - 为什么这个方法叫做
includes
而不是has
?
has
已被用作关键字了(Map.prototype.has
),
includes
用于元素(String.prototype.includes
)。集合的元素既可以被看作是键和也可以被看作值,这就是为什么有一个Set.prototype.has
(而不是includes
)。 - 适用于字符串,而不是字符。那么对于
Array.prototype.includes
方法而言,是不是存在不一致问题?
如果数组的includes
方法和字符串的includes
方法工作机制一样,它应该接受数组,而不是单个元素。但是两个includes
方法与indexOf
方法的例子保持一致;作为一般情况,字符被视为特殊情况和任意长度的字符串。
扩展阅读
(Domenic Denicola, Rick Waldron)
原文链接:
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂