数组拓展
扩展运算符
任何定义了遍历器(Iterator)接口的对象(参阅 Iterator 一章),都可以用扩展运算符转为真正的数组。
数组的空位
javascript
new Array(3) // [, , ,]
new Array(3) // [, , ,]
ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位。
forEach()
,filter()
,reduce()
,every()
和some()
都会跳过空位。 -map()
会跳过空位,但会保留这个值join()
和toString()
会将空位视为 undefined,而 undefined 和 null 会被处理成空字符串。
javascript
ES6 则是明确将空位转为 undefined。[,'a'].forEach((x,i) => console.log(i)); // 1
['a',,'b'].filter(x => true) // ['a','b']
[,'a'].every(x => x==='a') // true
[1,,2].reduce((x,y) => x+y) // 3
[,'a'].some(x => x !== 'a') // false
[,'a'].map(x => 1) // [,1]
[,'a',undefined,null].join('#') // "#a##"
[,'a',undefined,null].toString() // ",a,,"
[,'a'].forEach((x,i) => console.log(i)); // 1
['a',,'b'].filter(x => true) // ['a','b']
[,'a'].every(x => x==='a') // true
[1,,2].reduce((x,y) => x+y) // 3
[,'a'].some(x => x !== 'a') // false
[,'a'].map(x => 1) // [,1]
[,'a',undefined,null].join('#') // "#a##"
[,'a',undefined,null].toString() // ",a,,"
javascript
Array.from(['a',,'b']) //[ "a", undefined, "b" ]
[...['a',,'b']] // // [ "a", undefined, "b" ]
[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]
new Array(3).fill('a') // ["a","a","a"]
[...[,'a'].entries()] // [[0,undefined], [1,"a"]]
[...[,'a'].keys()] // [0,1]
[...[,'a'].values()] // [undefined,"a"]
[,'a'].find(x => true) // undefined
[,'a'].findIndex(x => true) // 0
// for of
let arr = [, ,];
for (let i of arr) {
console.log(1);
}
// 1 , 1
Array.from(['a',,'b']) //[ "a", undefined, "b" ]
[...['a',,'b']] // // [ "a", undefined, "b" ]
[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]
new Array(3).fill('a') // ["a","a","a"]
[...[,'a'].entries()] // [[0,undefined], [1,"a"]]
[...[,'a'].keys()] // [0,1]
[...[,'a'].values()] // [undefined,"a"]
[,'a'].find(x => true) // undefined
[,'a'].findIndex(x => true) // 0
// for of
let arr = [, ,];
for (let i of arr) {
console.log(1);
}
// 1 , 1
TIP
由于空位的处理规则非常不统一,所以建议避免出现空位。
静态方法
- Array.from()
- Array.of()
实例方法
- Array.prototype.copyWithin()
- Array.prototype.find()
- Array.prototype.findIndex()
- Array.prototype.fill()
- Array.prototype.keys()
- Array.prototype.values()
- Array.prototype.entries()
- Array.prototype.includes()
- Array.prototype.flat()
- Array.prototype.flatMap()
排序稳定性
ES2019 明确规定,Array.prototype.sort()的默认排序算法必须稳定。这个规定已经做到了,现在 JavaScript 各个主要实现的默认排序算法都是稳定的。