扩展运算符
扩展运算符(spread)是三个点(...
)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]
其可用于函数调用,作为参数序列
function push(array, ...items) {
array.push(...items);
}
扩展运算符后面还可以放置表达式,如果后面是一个空数组,则不产生任何效果
const arr = [
...(x > 0 ? ['a'] : []),
'b',
];
由于扩展运算符可以展开数组,因此不需要使用apply方法将数组转换为函数参数了
// ES5 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);
可以用来合并数组,不过,这两种方法都是浅拷贝,当数组内有引用型成员,如果修改了原数组成员的引用,会同步反映到新数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
可以与解构赋值结合,生成新的数组,但扩展运算符只能放在参数的最后一位,否则会报错
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest // []
const [first, ...rest] = ["foo"];
first // "foo"
rest // []
扩展运算符还可以将字符串转换为数组,其能正确识别4个四节的Unicode字符
[...'hello']
// [ "h", "e", "l", "l", "o" ]
'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3
任何具有Iterator
接口的对象都可以使用扩展运算符将其转为真正的数组,包括NodeList对象、Map和Set结构、Generator函数等
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]
const go = function*(){
yield 1;
yield 2;
yield 3;
};
[...go()] // [1, 2, 3]
Array.from()
Array.from
方法将类似数组的对象和可遍历的对象转换为真正的数组(包括NodeList集合、arguments对象等),其实,任何具有length
属性的对象都可以转换为数组。
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']
下面代码返回了一个具有三个成员的数组,而扩展运算符转换不了这个对象
Array.from({ length: 3 });
// [ undefined, undefined, undefined ]
Array.from
还可以接受第二个参数,作用类似于数组的map
方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如果map函数里面用到了this
关键字,还可以传入Array.from的第三个参数,用来绑定this
。
Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]
Array.of()
Array.of
方法用于将一组值,转换为数组。没有参数,就返回一个空数组
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
copyWithin()
数组实例的copyWithin
方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。
Array.prototype.copyWithin(target, start = 0, end = this.length)
//target(必需):从该位置开始替换数据。如果为负值,表示倒数
//start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数
//end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]
// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}
//此处相当于{0:undefined, 1:undefined, 2:undefined, 3:1, 4:undefined, length:5}.copyWithin(0,3);
//结果为{0:1, 1:undefined, 2:undefined, 3:1, 4:undefined, length:5}
//相当于{0:1, 3:1, length:5}
// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]
find()和findIndex()
数组实例的find
方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true
的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined
。
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
}) // 10
其回调函数包括3个参数,当前项的值、索引以及整个数组
数组实例的findIndex
方法的用法与find
方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2
这两个方法都可以接受第二个参数,用来绑定回调函数的this
对象。它们都可以发现NaN,弥补了indexOf
方法的不足
fill()
fill
方法使用给定值,填充一个数组。数组原有的元素会被覆盖
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
fill
方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
该方法填充的方式为浅拷贝,若填充的类型是对象,则只是同一个内存地址的对象。
entires()、keys() 和 values()
ES6 提供三个新的方法——entries()
,keys()
和values()
——用于遍历数组。它们都返回一个遍历器对象。其中entries()
是对键值对的遍历,keys()
是对键的遍历,values()
是对值的遍历。可以使用for...of
得到相应的值。
for (let [index,value] of [1,2,3].entries()){
console.log(index,value);
}
for (let index of [1,2,3].keys()){
console.log(index);
}
for (let value of [1,2,3].values()){
console.log(value);
}
如果不使用for...of
循环,可以手动调用遍历器对象的next
方法,进行遍历
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
includes()
Array.prototype.includes
方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes
方法类似
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
方法的第二个参数表示搜索的起始位置,默认为0。
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true