JavaScript 中Array.from方法

Array.from 是 JavaScript 中用于从类数组对象(如 argumentsNodeList)或可迭代对象(如字符串、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. 将 SetMap 转换为数组
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]

注意事项

  • 如果不需要 mapFunctionthisArgArray.from(arrayLike) 就已经足够。
  • Array.prototype.map 的不同点是 Array.from 可以直接处理类数组对象,而 map 只能在真正的数组上使用。

这是一个强大的工具,尤其在处理类数组数据时极为便利!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值