调用 new Array()构造器时, 根据传入参数的类型与数量的不同,实际上会导致一些不同的结果。
1 | items = new Array(3, "2"); |
如果使用多个参数(无
论是否为数值类型)来调用,这些参数也会成为目标数组的项。
1 | let items = Array.of("2"); |
向函数传递参数,使用 Array.of() 而非 Array 构
造器能够确保行为一致。
1 | function createArray(arrayCreator, value) { |
若想将类数组的 arguments 对
象当做数组来使用,那么你首先需要对其进行转换。
1 | function makeArray(arrayLike) { |
可以调用数组原
生的 slice() 方法来减少代码量
1 | function makeArray(arrayLike) { |
它能正常工作是因为将 slice() 方法的 this 设置为类
数组对象, slice() 只需要有数值类型的索引与长度属性就能正常工作,而类数组对象能满
足这些要求。
Array.from()
1 | function doSomething() { |
find() findIndex()
find() 方法会返回匹配的值,而 findIndex() 方法则会返回匹配位置
的索引。
1
2
3 let numbers = [25, 30, 35, 40, 45];
console.log(numbers.find(n => n > 33)); // 35
console.log(numbers.findIndex(n => n > 33)); // 2
fill()
用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。arr.fill(value[, start[, end]])
copyWithin()
在当前数组内部,将指定位置的成员复制到其他位置
1 | Array.prototype.copyWithin(target, start = 0, end = this.length) |