mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-24 18:32:22 +00:00
docs(array): edit array/includes
This commit is contained in:
parent
febdb474e7
commit
3ff9b184e4
@ -334,15 +334,15 @@ console.log(entries.next().value); // [2, 'c']
|
||||
|
||||
## 数组实例的 includes()
|
||||
|
||||
`Array.prototype.includes`方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的`includes`方法类似。该方法属于ES7/ES2016,但Babel转码器已经支持。
|
||||
`Array.prototype.includes`方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的`includes`方法类似。ES2016 引入了该方法。
|
||||
|
||||
```javascript
|
||||
[1, 2, 3].includes(2); // true
|
||||
[1, 2, 3].includes(4); // false
|
||||
[1, 2, NaN].includes(NaN); // true
|
||||
[1, 2, 3].includes(2) // true
|
||||
[1, 2, 3].includes(4) // false
|
||||
[1, 2, NaN].includes(NaN) // true
|
||||
```
|
||||
|
||||
该方法的第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。
|
||||
该方法的第二个参数表示搜索的起始位置,默认为`0`。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为`-4`,但数组长度为`3`),则会重置为从`0`开始。
|
||||
|
||||
```javascript
|
||||
[1, 2, 3].includes(3, 3); // false
|
||||
@ -357,7 +357,7 @@ if (arr.indexOf(el) !== -1) {
|
||||
}
|
||||
```
|
||||
|
||||
`indexOf`方法有两个缺点,一是不够语义化,它的含义是找到参数值的第一个出现位置,所以要去比较是否不等于-1,表达起来不够直观。二是,它内部使用严格相等运算符(===)进行判断,这会导致对`NaN`的误判。
|
||||
`indexOf`方法有两个缺点,一是不够语义化,它的含义是找到参数值的第一个出现位置,所以要去比较是否不等于`-1`,表达起来不够直观。二是,它内部使用严格相等运算符(`===`)进行判断,这会导致对`NaN`的误判。
|
||||
|
||||
```javascript
|
||||
[NaN].indexOf(NaN)
|
||||
@ -379,7 +379,7 @@ const contains = (() =>
|
||||
? (arr, value) => arr.includes(value)
|
||||
: (arr, value) => arr.some(el => el === value)
|
||||
)();
|
||||
contains(["foo", "bar"], "baz"); // => false
|
||||
contains(['foo', 'bar'], 'baz'); // => false
|
||||
```
|
||||
|
||||
另外,Map 和 Set 数据结构有一个`has`方法,需要注意与`includes`区分。
|
||||
|
Loading…
x
Reference in New Issue
Block a user