Array.from()
是 JavaScript 中用于将类数组对象(array-like)或可迭代对象(iterable)转换为真实数组的一个非常有用的方法。
📌 一、基本语法
Array.from(arrayLike, mapFn?, thisArg?)
参数说明:
参数 | 类型 | 描述 |
---|---|---|
arrayLike | 对象 | 一个类数组对象或可迭代对象(如字符串、Map、Set、DOM NodeList 等) |
mapFn | 函数(可选) | 类似于 map() 的回调函数,用于对每个元素进行处理 |
thisArg | 任意值(可选) | 执行 mapFn 时使用的 this 值 |
✅ 二、作用详解
1. 把类数组对象转成数组
类数组对象:有
length
属性,并可以通过索引访问元素,但没有数组的方法(如push
,slice
等)
示例:
const arrayLike = {0: 'a',1: 'b',2: 'c',length: 3
};const arr = Array.from(arrayLike);
console.log(arr); // ['a', 'b', 'c']
2. 把字符串转成字符数组
Array.from('hello');
// 输出: ['h', 'e', 'l', 'l', 'o']
相比
str.split('')
,Array.from()
更适合处理带 Unicode 字符的字符串。
3. 把 Set / Map 转成数组
const set = new Set([1, 2, 3]);
Array.from(set); // [1, 2, 3]const map = new Map([['a', 1], ['b', 2]]);
Array.from(map); // [['a', 1], ['b', 2]]
4. 把 arguments 对象转成数组(ES5 中常用)
function example() {return Array.from(arguments);
}
example(1, 2, 3); // [1, 2, 3]
5. 结合 DOM NodeList 使用
const divs = document.querySelectorAll('div');
const divArray = Array.from(divs);
divArray.forEach(div => console.log(div));
🔁 三、使用 mapFn
映射处理
你可以在创建数组的同时,对每个元素进行映射处理,相当于:
Array.from(obj, x => fn(x))
示例:
Array.from({ length: 5 }, (_, i) => i * 2);
// 输出: [0, 2, 4, 6, 8]
这个用法非常适合用来生成数字序列、初始化数组等场景。
🧪 四、实用技巧示例
1. 生成指定长度的数字数组(从0开始)
Array.from({ length: 5 }, (_, i) => i);
// [0, 1, 2, 3, 4]
2. 生成随机数数组
Array.from({ length: 5 }, () => Math.floor(Math.random() * 100));
// 示例输出: [23, 78, 11, 45, 90]
3. 去重并转成数组
const str = 'abacdef';
Array.from(new Set(str)); // ['a', 'b', 'c', 'd', 'e', 'f']
🆚 五、与 Array.prototype.slice.call()
的区别
在 ES5 中我们经常这样把类数组转成数组:
Array.prototype.slice.call(arrayLike);
但在 ES6 中,推荐使用更简洁、语义更强的:
Array.from(arrayLike);
📝 总结
特性 | Array.from() |
---|---|
输入类型 | 类数组、可迭代对象 |
是否改变原数组 | ❌ 不会修改原数组 |
是否返回新数组 | ✅ 返回一个新的数组 |
支持 .map() 式处理 | ✅ 支持 mapFn 回调 |
兼容性 | ✅ 大多数现代浏览器都支持(IE 不支持) |