Array.from
是 JavaScript 中用于从类数组对象(如 arguments
、NodeList
)或可迭代对象(如字符串、Set、Map)创建一个新的数组实例的方法。它常见的用法包括数组转换、数据映射和去重操作等。
语法
Array.from(arrayLike, mapFunction, thisArg)
- arrayLike: 必填,表示想要转换为数组的类数组对象或可迭代对象。
- mapFunction: 可选,对数组中的每个元素执行的映射函数(类似于
Array.prototype.map
)。 - thisArg: 可选,执行
mapFunction
时的this
值。
基本用法示例
1. 从类数组对象创建数组
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.from(arrayLike);
console.log(arr); // ['a', 'b']
2. 从字符串创建数组
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
3. 将 Set
或 Map
转换为数组
const set = new Set([1, 2, 3]);
const arrFromSet = Array.from(set);
console.log(arrFromSet); // [1, 2, 3]
const map = new Map([[1, 'a'], [2, 'b']]);
const arrFromMap = Array.from(map);
console.log(arrFromMap); // [[1, 'a'], [2, 'b']]
使用 mapFunction
进行映射
4. 数据映射
const numbers = [1, 2, 3];
const squared = Array.from(numbers, x => x ** 2);
console.log(squared); // [1, 4, 9]
5. 生成特定序列
const sequence = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(sequence); // [1, 2, 3, 4, 5]
其他应用场景
6. 将 arguments
转换为数组
function example() {
const args = Array.from(arguments);
console.log(args);
}
example(1, 2, 3); // [1, 2, 3]
7. 数组去重
const arr = [1, 2, 2, 3, 3];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3]
8. 填充默认值
const defaultArr = Array.from({ length: 5 }, () => 0);
console.log(defaultArr); // [0, 0, 0, 0, 0]
注意事项
- 如果不需要
mapFunction
或thisArg
,Array.from(arrayLike)
就已经足够。 - 与
Array.prototype.map
的不同点是Array.from
可以直接处理类数组对象,而map
只能在真正的数组上使用。
这是一个强大的工具,尤其在处理类数组数据时极为便利!