ES6 - 数组属性

tech2022-07-04  182

4-1.扩展运算符

扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

console.log(...[1,2,3,4,5]); // 1 2 3 4 5 console.log(1,...[2,3,4],5); // 1 2 3 4 5

如果扩展运算符后面是一个空数组,则不产生任何效果。

console.log(...[]); // 输出空

4-2.代替函数的 apply 方法

由于扩展运算符可以展开数组,所以不再需要apply方法,将数组转为函数的参数了。

// ES5 的写法 function f(x, y, z) { // ... } var args = [0, 1, 2]; f.apply(null, args); // ES6的写法 function f(x, y, z) { // ... } let args = [0, 1, 2]; f(...args);

4-3. Array.from()

Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。

let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; // ES5的写法 var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c'] // ES6的写法 let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

4-4. Array.of()

Array.of方法用于将一组值,转换为数组。

Array.of(3, 11, 8) // [3,11,8] Array.of(3) // [3] Array.of(3).length // 1

4-5. copyWithin()

在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。

Array.prototype.copyWithin(target, start = 0, end = this.length)

参数:

targent(必须):从该位置替换数据。如果为负值,表示为倒数。start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。 [1,2,3,4,5].copyWithin(1,3,4); // [1, 4, 3, 4, 5] // -2相当于3号位,-1相当于4号位 [1, 2, 3, 4, 5].copyWithin(0, -2, -1) // [4, 2, 3, 4, 5]

4-6. entries(),keys() 和 values()

entries(),keys()和values()——用于遍历数组。

区别:唯一的区别是keys()是对键名的遍历,values()是对键值的遍历,entries()是对键值对的遍历

for (let index of ['a', 'b'].keys()) { console.log(index); } // 0 // 1 for (let elem of ['a', 'b'].values()) { console.log(elem); } // 'a' // 'b' for (let [index, elem] of ['a', 'b'].entries()) { console.log(index, elem); } // 0 "a" // 1 "b"

4-7. includes()

Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。

includes(searchvalue, start) [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, NaN].includes(NaN) // true

参数:

searchvalue(必须):要查找的字符串 or 数组元素。start(可选): 可选,设置从那个位置开始查找,默认为 0。
最新回复(0)