类数组对象是具有length属性和数值键的非数组对象,如arguments、NodeList;Array.from通过读取length及索引值将其转为真数组,并支持可迭代对象与映射函数,常用于DOM操作或参数处理。

Array.from 方法可以将类数组对象(array-like object)转换为真正的数组,主要通过读取对象的 length 属性,并根据索引从 0 到 length - 1 依次提取属性值,构造出一个新数组。
例如:
const arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
示例:
const arrayLike = { 0: 'x', 1: 'y', length: 2 };
const arr = Array.from(arrayLike);
<p>console.log(arr); // ['x', 'y']
console.log(Array.isArray(arr)); // true
带映射函数的例子:
立即学习“Java免费学习笔记(深入)”;
const arrayLike = { 0: 2, 1: 4, 2: 6, length: 3 };
const doubled = Array.from(arrayLike, x => x * 2);
<p>console.log(doubled); // [4, 8, 12]
这相当于先生成数组 [2, 4, 6],然后对每个元素执行 x => x * 2。
Array.from(document.querySelectorAll('div'))
Array.from(arguments) 可替代 Array.prototype.slice.call(arguments)
Array.from('hello') 得到 ['h', 'e', 'l', 'l', 'o']基本上就这些。Array.from 提供了一种简洁、标准的方式,把看起来像数组的东西变成真正的数组,方便使用 map、filter 等方法。
以上就是JavaScript 的 Array.from 方法如何将类数组对象转换为真实数组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号