欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ES7新功能之——includes()

程序员文章站 2022-07-16 14:19:34
...

说起ES7(ECMAScript 2016),不得不先提出这么一个新功能——Array.prototype.includes()

我们之前判断一个元素是否在数组中主要是通过indexOf()来确定,准确而言indexOf()的返回值是某个值在数组中的索引,如果我们的目的是确定一个元素是否存在于数组中,那么使用indexOf()显然不是最好的选择,理由很简单:当判断某个值的是否存在时我们希望得到一个布尔值,而不是数值。

Array.prototype.includes()做的恰恰是这件事,它能确定数组中是否包含给定元素,有就返回 true,否则返回 false 。

<script>
    var arr = ['one', 'two', 'three']
    life.includes('one')          // true   
    life.includes('five')         // false
</script>

深入标准

Array.prototype.includes ( searchElement [ , fromIndex ] )

searchElement —— 要查找的元素。

fromIndex (可选的) — 开始查询的起始索引。

我们来看一下规范中的内容:

# includes

# [1] searchs in ascending order

# 搜索按升序进行

> Array(10000000).concat(4).includes(4)

true # [Time] 500 miliseconds 耗时 500ms

> [4].concat(Array(10000000)).includes(4)

true # [Time] 90 miliseconds 耗时 90ms



# [2] uses SameValueZero algorithm

# 使用 SameValueZero 算法比较

> [NaN].indexOf(NaN)

-1

> [NaN].includes(NaN)

true



# [3] if found at any position returns true

# otherwise, false is returned

# 在任何位置找到都会返回 true,否则返回 false

> [1, 2, 3].includes(2)

true

> [1, 2, 3].includes(7)

false



# [4] it treats missing array elements as undefined

# 将数组中缺失的元素视为 undefined

> [1, , 3].indexOf(undefined)

-1

> [1, , 3].includes(undefined)

true

下面对以上代码做一下分析:

(1)这里的区别是元素 4 的位置。在第一个例子中 4 位于数组末尾,所以 includes 方法会搜索整个数组。按规范,.includes() 方法会在找到 searchElement 后立即返回,所以第二个例子执行地更快。

(2)SameValueZero 算法与严格相等比较(.indexOf()采用)的最大区别就是它允许检测 NaN 元素。

(3)元素被找到就返回 true,否则返回 false。不再使用索引作为结果了

(4)与 .indexOf() 相反,.includes() 并不会跳过缺失的数组元素,而会将其视为 undefined。

还有一个要点是fromIndex

规范中是这样写的:

可选的第二参数 fromIndex 默认值为 0(这意味整个数组都会被搜索)。如果这个参数的值大于或等于数组长度,则会直接返回 false ,数组将不会被搜索。如果值为是负数,则代表相对于数组末尾的偏移量。如果偏移量超过数组长度,则整个数组都会被搜索。

# fromIndex



# [1] it defaults to 0

# 默认为 0

> [1,2,3].includes(1)

true



# [2] if >= array.length, false is returned

# 如果 >= array.length, 返回 false

> [1,2,3].includes(1, 10)

false



# [3] if negative, it is used as the offset, i.e.

# 如果为负数,则被用作偏移

# offset = array.length + fromIndex

> [1,2,3].includes(3, -2) # fromIndex = 3 (array length) + -2 (fromIndex) = 1

true



# [4] if offset < 0, the whole array is searched

# 如果根据偏移计算的搜索起始索引 < 0,则整个数组都会被搜索

> [1,2,3].includes(1, -5) # fromIndex = 0

true

根据以上内容:

(1)如果不提供 fromIndex 参数则默认其为 0 ,这时整个数组都将被搜索。

(2)当 fromIndex 大于数组长度时,.includes() 立即返回 false

(3)如果 fromIndex 是负值, 那么起始索引计算方式为 array.length — fromIndex 。这在搜索数组末尾元素时很有用。例如 fromIndex = -5 意味着只搜索最后 5 个元素。

(4)为了避免 .includes() 执行中断,当计算得到的起始索引小于 0 时,整个数组会被搜索。

以上就是关于includes()的一些学习和理解。

相关标签: ES7 includes