array.from 是 javascript 中将类数组或可迭代对象转换为真正数组的方法,支持映射函数、兼容性好、语义清晰;类数组需有 length 属性和数字索引,如 arguments、nodelist、htmlcollection;字符串、set、map 等可迭代对象也适用。

Array.from 是 JavaScript 中专门用来将类数组(array-like)对象或可迭代(iterable)结构转换为真正数组的方法,语法简洁、兼容性好(ES6+),比传统的 [].slice.call() 更直观可靠。
哪些结构算“类数组”?
类数组对象指具有 length 属性 和 **按数字索引存储元素** 的普通对象,但没有数组的内置方法(如 map、filter)。常见例子包括:
-
arguments对象(函数内部) -
NodeList(如document.querySelectorAll('div')返回值) -
HTMLCollection(如document.getElementsByTagName('p')) - 手动构造的带
0、1、length的对象
基本用法:只传类数组参数
最常用写法,直接传入类数组对象,返回新数组:
// 示例:转换 NodeList
const divs = document.querySelectorAll('div');
const divArray = Array.from(divs); // ✅ 得到真正的数组
divArray.forEach(el => el.classList.add('active')); // 可直接调用 forEach
<p>// 示例:转换 arguments(ES5 函数中)
function example() {
const args = Array.from(arguments); // ✅ 替代 [].slice.call(arguments)
return args.map(x => x * 2);
}</p>
进阶用法:配合映射函数(mapFn)
第二个参数可传一个映射函数,类似 Array.prototype.map,在转换同时处理每个元素:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 函数接收当前项、索引、原类数组对象作为参数
- 避免先转数组再调
map,减少一次遍历
// 一行提取所有 input 的 value 并转为数字
const inputs = document.querySelectorAll('input');
const values = Array.from(inputs, input => Number(input.value));
<p>// 构造带索引的对象数组
const list = Array.from('abc', (char, i) => ({ index: i, char }));
// → [{index:0,char:'a'}, {index:1,char:'b'}, {index:2,char:'c'}]</p>
注意点和常见坑
不是所有“像数组”的东西都能直接用 Array.from:
-
纯对象(无 length 或数字索引)不行:比如
{a:1, b:2}不是类数组,会得到空数组[] -
字符串是可迭代的,不是类数组:但
Array.from('hi')仍有效,因为它实现了Symbol.iterator,结果是['h','i'] -
Set/Map 是可迭代的:也可用
Array.from(new Set([1,2,2]))去重转数组 →[1,2] -
稀疏类数组需留意:若索引不连续(如只有
0和5),length=6,则中间位置为undefined,Array.from会如实保留
对比其他转换方式
相比老方法,Array.from 更安全清晰:
-
[].slice.call(arrayLike):依赖原型链,若arrayLike没有slice方法会报错 -
Array.prototype.slice.call(arrayLike):同上,且写法冗长 -
Spread syntax [...arrayLike]:更短,但要求对象必须可迭代(NodeList在较新环境支持,arguments在箭头函数中不可用)
推荐优先用 Array.from,语义明确、兼容性广、支持映射逻辑,不复杂但容易忽略它的第二参数能力。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










