Array.from()
用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象,(包括 ES6 新增的数据结构 Set 和 Map)
-
类似数组的对象(array-like object)
- 常见的类似数组的对象是 DOM 操作返回的 NodeList 集合,以及函数内部的
arguments
对象,Array.from
都可以将它们转为真正的数组 - 本质特征只有一点,即必须有
length属性
Array.from
还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组
// --类似数组的对象-01 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'] // 两个参数-01 Array.from(arrayLike, x => x + 'char'); // 等同于 Array.from(arrayLike).map(x => x + 'char'); // 两个参数-02 Array.from([1, 2, 3], (x) => x * x) // [1, 4, 9] // --类似数组的对象-02 Array.from({ length: 3 }); // [ undefined, undefined, undefined ] // --NodeList对象 let ps = document.querySelectorAll('p'); Array.from(ps).filter(p => { return p.textContent.length > 100; }); // --arguments对象 function foo() { var args = Array.from(arguments); // ... } 复制代码
- 常见的类似数组的对象是 DOM 操作返回的 NodeList 集合,以及函数内部的
-
可遍历(iterable)的对象
// 字符串 Array.from('hello') // ['h', 'e', 'l', 'l', 'o'] // Set let namesSet = new Set(['a', 'b']) Array.from(namesSet) // ['a', 'b'] // 数组 Array.from([1, 2, 3]) // [1, 2, 3] 复制代码
Array.of()
用于将一组值,转换为数组
-
Array.of
总是返回参数值组成的数组。如果没有参数,就返回一个空数组Array.of(3, 11, 8) // [3,11,8] Array.of(3) // [3] Array.of(3).length // 1 Array.of() // [] 复制代码
copyWithin()
在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。
-
使用这个方法,会
修改当前数组
-
它接受三个参数。
target
(必需):从该位置开始替换数据。如果为负值,表示倒数。start
(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。end
(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
-
这三个参数都应该是数值,如果不是,会自动转为数值。
// 将从 3 号位直到数组结束的成员,复制到从 0 号位开始的位置, [1, 2, 3, 4, 5].copyWithin(0, 3) // [4, 5, 3, 4, 5] // 将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} // 将2号位到数组结束,复制到0号位 let i32a = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5] // 对于没有部署 TypedArray 的 copyWithin 方法的平台 // 需要采用下面的写法 [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5] 复制代码