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
@ -332,17 +332,17 @@ console.log(entries.next().value); // [1, 'b']
|
||||
console.log(entries.next().value); // [2, 'c']
|
||||
```
|
||||
|
||||
## 数组实例的includes()
|
||||
## 数组实例的 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,13 +379,13 @@ 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`区分。
|
||||
另外,Map 和 Set 数据结构有一个`has`方法,需要注意与`includes`区分。
|
||||
|
||||
- Map结构的`has`方法,是用来查找键名的,比如`Map.prototype.has(key)`、`WeakMap.prototype.has(key)`、`Reflect.has(target, propertyKey)`。
|
||||
- Set结构的`has`方法,是用来查找值的,比如`Set.prototype.has(value)`、`WeakSet.prototype.has(value)`。
|
||||
- Map 结构的`has`方法,是用来查找键名的,比如`Map.prototype.has(key)`、`WeakMap.prototype.has(key)`、`Reflect.has(target, propertyKey)`。
|
||||
- Set 结构的`has`方法,是用来查找值的,比如`Set.prototype.has(value)`、`WeakSet.prototype.has(value)`。
|
||||
|
||||
## 数组的空位
|
||||
|
||||
@ -406,7 +406,7 @@ Array(3) // [, , ,]
|
||||
|
||||
上面代码说明,第一个数组的0号位置是有值的,第二个数组的0号位置没有值。
|
||||
|
||||
ES5对空位的处理,已经很不一致了,大多数情况下会忽略空位。
|
||||
ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位。
|
||||
|
||||
- `forEach()`, `filter()`, `every()` 和`some()`都会跳过空位。
|
||||
- `map()`会跳过空位,但会保留这个值
|
||||
@ -435,7 +435,7 @@ ES5对空位的处理,已经很不一致了,大多数情况下会忽略空
|
||||
[,'a',undefined,null].toString() // ",a,,"
|
||||
```
|
||||
|
||||
ES6则是明确将空位转为`undefined`。
|
||||
ES6 则是明确将空位转为`undefined`。
|
||||
|
||||
`Array.from`方法会将数组的空位,转为`undefined`,也就是说,这个方法不会忽略空位。
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user