📜  JavaScript 数组 from() 方法(1)

📅  最后修改于: 2023-12-03 15:16:12.725000             🧑  作者: Mango

JavaScript数组from()方法

JavaScript 的数组对象提供了一个名为 from() 的方法,它可以从一个类似数组或可迭代对象中创建一个新的数组。这个方法返回一个新的数组,这个数组包含了传入的可迭代对象中所有可以被迭代的元素。

语法
Array.from(arrayLike[, mapFn[, thisArg]])
参数
  • arrayLike(必选):一个使用迭代器接口的对象,例如 Array 或者 arguments。或者任何实现了迭代器接口的对象。
  • mapFn(可选):对每个元素进行 map 操作的回调函数,它会将当前迭代的元素作为第一个参数传入进去。
  • thisArg(可选):回调函数 mapFn 的执行上下文。
示例
1. 从字符串中创建数组
const str = 'Hello World';
const arr = Array.from(str);
console.log(arr); // [ 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' ]
2. 从 Set 对象中创建数组
const set = new Set([1, 2, 3]);
const arr = Array.from(set);
console.log(arr); // [ 1, 2, 3 ]
3. 从 Map 对象中创建数组
const map = new Map([['name', 'Tom'], ['age', 18]]);
const arr = Array.from(map);
console.log(arr); // [ [ 'name', 'Tom' ], [ 'age', 18 ] ]
4. 将 NodeList 转换为数组
const list = document.querySelectorAll('p');
const arr = Array.from(list);
console.log(arr); // [ <p>, <p>, <p> ]
5. 使用 mapFn 回调函数来操作元素
const arr = Array.from([1, 2, 3], num => num * 2);
console.log(arr); // [ 2, 4, 6 ]
总结

JavaScript 中的 from() 方法可以从一个类似数组或可迭代对象中创建一个新的数组,并且提供了对每个元素进行操作的回调函数 mapFn。这个方法使得我们可以轻松地将不同类型的数据结构转换成数组,从而方便我们进行遍历等操作。