一.扩展运算符
类似于rest的反向操作,将一个数组变为用都好分割的参数序列,展开数组
console.log(...[1, 2, 3])
// 1 2 3
应用1:深度复制数组
let arr = [1,2,3,4];
let arr2 = [...arr];
arr.copyWithin(1,2,3);
arr // 1,3,3,4
arr2 // 1,2,3,4
应用2:合并数组
// ES5
[1, 2].concat(more)
// ES6
[1, 2, ...more]
应用3:和解构赋值结合,需在最后一个位置
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.字符串
[...'hello']; //'h','e','l','l','o'
5.任何实现了Iterator接口的对象都能都可以使用扩展运算符
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
二.Array的方法
1.Array.from(arrayLike,fn) ,fn可以对arrayLike中每一项做操作
将类似于数组的对象(具有length属性)和具有可遍历的对象(Set和Map)转化为真正的数组
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']
let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
2.Array.of(),将一组值转化为数组
Array.of(3, 11, 8) // [3,11,8]
3.copyWithin(),
Array.prototype.copyWithin(target, start = 0, end = this.length)
// 选取start-end范围内的数值,从target开始替换,有多少替换多少
[1, 2, 3, 4, 5 , 6,7,8,9,10].copyWithin(0, 2,5);
// [3, 4, 5, 4, 5, 6, 7, 8, 9, 10]
4.数组实例的 find() 和 findIndex()
find()方法找到数组中第一个符合条件的值,并返回值
findIndex()方法返回第一个符合条件的值的下标
5.数组实例的 fill()
填充一个数组
new Array(3).fill(7)
// [7, 7, 7]
6.数组实例的 entries(),keys() 和 values()
目前chrome不支持
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"
7.数组实例的 includes()
返回boolean,判断数组包含某一个值
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
三.Array的空位处理
空位不是undefined,array空位处理严重不一致,所以尽量避免出现空位