# Array.of()
根据传入的参数,无论参数什么类型,创建一个包含所有参数的数组。 目的是代替 new Array(). 如果传入new Array()的参数是一个数字,则表示为数组长度
Array.of(element0[, element1[, ...[, elementN]]])
参数
elementN
任意个参数,将按顺序成为返回数组中的元素。
返回值
新的 Array 实例。
let items = Array.of(1, 2);
console.log(item.length); // 2
console.log(items[0]); // 1
console.log(items[1]); // 2
let items = Array.of(2);
console.log(item.length); // 1
console.log(items[0]); // 2
let items = Array.of('2');
console.log(item.length); // 1
console.log(items[0]); // '2'
# Array.from()
将可迭代对象或者类数组对象转化为数组。
Array.from(arrayLike[, mapFn[, thisArg]])
参数
arrayLike
想要转换成数组的伪数组对象或可迭代对象。
mapFn 可选
如果指定了该参数,新数组中的每个元素会执行该回调函数。
thisArg 可选
可选参数,执行回调函数 mapFn 时 this 对象。
返回值
一个新的数组实例。
转化类数组对象:
// es5
function makeArray() {
var args = Array.prototype.slice(arguments);
}
// es6
function makeArray() {
var args = Array.from(arguments);
}
转可迭代对象:
let numbers = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
let numbers2 = Array.from(numbers);
console.log(numbers2); // [1,2,3]
# find(), findIndex()
find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
arr.find(callback[, thisArg])
callback
在数组每一项上执行的函数,接收 3 个参数:
element
当前遍历到的元素。
index可选
当前遍历到的索引。
array可选
数组本身。
thisArg可选
执行回调时用作this 的对象。
返回值
数组中第一个满足所提供测试函数的元素的值,否则返回 undefined。
let numbers = [25, 30, 35, 40, 45];
console.log(numbers.find(n => n >33)); // 35
console.log(numbers.findIndex(n => n >33)); // 2
# fill()
fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
arr.fill(value[, start[, end]])
参数
value
用来填充数组元素的值。
start 可选
起始索引,默认值为0。
end 可选
终止索引,默认值为 this.length。
返回值
修改后的数组。
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
# copyWithin()
copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
arr.copyWithin(target[, start[, end]])
target
0 为基底的索引,复制序列到该位置。如果是负数,target 将从末尾开始计算。
如果 target 大于等于 arr.length,将会不发生拷贝。如果 target 在 start 之后,复制的序列将被修改以符合 arr.length。
start
0 为基底的索引,开始复制元素的起始位置。如果是负数,start 将从末尾开始计算。
如果 start 被忽略,copyWithin 将会从0开始复制。
end
0 为基底的索引,开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。如果是负数, end 将从末尾开始计算。
如果 end 被忽略,copyWithin 方法将会一直复制至数组结尾(默认为 arr.length)。
返回值
改变后的数组。
const array1 = ['a', 'b', 'c', 'd', 'e'];
// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]
// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]