ECMAScript2016(ES7)新特性
# 概述
ECMAScript2016于2016年6月正式发布, 本文会介绍ECMAScript2016(ES7),即ECMAScript的第7个版本的新特性。
以下摘自官网:ecma-262 (opens new window)
ECMAScript 2016 was the first ECMAScript edition released under Ecma TC39's new yearly release cadence and open development process. A plain-text source document was built from the ECMAScript 2015 source document to serve as the base for further development entirely on GitHub. Over the year of this standard's development, hundreds of pull requests and issues were filed representing thousands of bug fixes, editorial fixes and other improvements. Additionally, numerous software tools were developed to aid in this effort including Ecmarkup, Ecmarkdown, and Grammarkdown. ES2016 also included support for a new exponentiation operator and adds a new method to Array.prototype called includes.
# ECMAScript2016(ES7)
ES7只有两个新特性
Array.prototype.includes
:用于判断数组是否存在某元素**
:指数运算符
# includes
includes
方法会遍历数组(从索引0开始逐个检查,直到找到目标值或搜索完整个数组,如果存在该元素,则返回true
,否则返回false
。
includes
的时间复杂度平均情况为O(n),其中n为数组长度。
# 对比JS其他搜索方法
方法 | 时间复杂度 | 是否提前终止 | 适用场景 |
---|---|---|---|
includes | O(n) | 是 | 检查值是否存在 |
indexOf | O(n) | 是 | 获取值的索引 |
find | O(n) | 是 | 复杂条件搜索 |
some | O(n) | 是 | 条件匹配(返回布尔值) |
Set.has | O(1) | 是 | 检查值是否存在 |
因此对于高频搜索或者是大数据量搜索,建议先将数组转为Set
,再使用Set.has
方法。
# 注意事项
includes
方法可以查找NaN
,而indexOf
和indexOf
方法不能查找NaN
。includes
方法是不区分+0
和-0
# 浏览器兼容性

# **
**
运算符用于指数运算,即返回底数的指数次幂。比如x**y
和Math.pow(x,y)
是等价的
# 浏览器兼容性
