【JavaScript】Array.from及其相关用法详解

JavaScript 中的 Array.from 方法是一个强大的工具,可以轻松地将类数组对象或可迭代对象转换为数组,并通过可选的回调函数对每个元素进行自定义处理。本文将详细介绍 Array.from 的基本用法、实际场景中的应用,以及它如何与其他 JavaScript 特性相结合提升代码的简洁性和可读性。

一、Array.from 方法概述

1. 方法介绍

Array.from 是 ES6 引入的一个静态方法,用于从类数组对象(具有 length 属性的对象)或可迭代对象(如字符串、Set、Map)创建一个新的数组实例。

语法:

Array.from(arrayLike, mapFunction, thisArg)
  • arrayLike:要转换为数组的类数组对象或可迭代对象。
  • mapFunction(可选):一个函数,对每个元素执行转换。
  • thisArg(可选):执行 mapFunction 时的 this 值。

返回值:

  • 一个新的数组。

2. 示例演示

基本用法:

const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const result = Array.from(arrayLike);
console.log(result); // ['a', 'b']

const str = 'hello';
console.log(Array.from(str)); // ['h', 'e', 'l', 'l', 'o']

mapFunction 的用法:

const nums = [1, 2, 3];
const doubled = Array.from(nums, x => x * 2);
console.log(doubled); // [2, 4, 6]

二、结合实际场景的使用

1. 初始化二维数组

在一些算法题中,我们可能需要初始化一个二维数组。利用 Array.from 可以轻松实现:

const numRows = 3;
const rows = Array.from({ length: numRows }, () => []);
console.log(rows); // [[], [], []]

这个例子中:

  • { length: numRows } 定义了一个长度为 numRows 的类数组对象。
  • () => [] 是一个回调函数,用于为每一行生成一个新的空数组。

实际应用: 在模拟二维矩阵时,rows 数组可以用于存储每一行的数据,例如在处理 Z 字形转换的算法中。

Z 字形转换示例:

const numRows = 3;
const rows = Array.from({ length: numRows }, () => []);
const input = 'PAYPALISHIRING';
let direction = 1, row = 0;

for (const char of input) {
    rows[row].push(char);
    if (row === 0 || row === numRows - 1) direction *= -1;
    row += direction;
}

console.log(rows.map(r => r.join('')).join('')); // PAHNAPLSIIGYIR

2. 从可迭代对象创建数组

对于字符串、Set 或 Map,Array.from 提供了一种简单的方法将它们转换为数组。

字符串转数组:

const str = 'JavaScript';
console.log(Array.from(str)); // ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

从 Set 转数组(去重):

const set = new Set([1, 2, 2, 3]);
console.log(Array.from(set)); // [1, 2, 3]

从 Map 转数组:

const map = new Map([[1, 'a'], [2, 'b']]);
console.log(Array.from(map)); // [[1, 'a'], [2, 'b']]

3. 构造特定范围的数组

可以通过 Array.from 快速生成特定范围的数组。

生成从 0 到 9 的数字数组:

const range = Array.from({ length: 10 }, (_, i) => i);
console.log(range); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

生成平方数数组:

const squares = Array.from({ length: 5 }, (_, i) => i ** 2);
console.log(squares); // [0, 1, 4, 9, 16]

三、注意事项

1. 类数组对象必须有 length 属性

Array.from 的第一个参数必须是类数组对象或可迭代对象。类数组对象需要显式地定义 length 属性。

无效示例:

const obj = { 0: 'a', 1: 'b' };
console.log(Array.from(obj)); // []

修正:

const obj = { 0: 'a', 1: 'b', length: 2 };
console.log(Array.from(obj)); // ['a', 'b']

2. 回调函数中的索引

Array.from 的回调函数中,除了当前元素,还可以访问其索引。

示例:

const arr = Array.from({ length: 5 }, (val, index) => index * 2);
console.log(arr); // [0, 2, 4, 6, 8]

3. 性能注意

Array.from 的回调函数可能会对性能产生一定的影响,特别是在处理大规模数据时,建议在性能要求较高的场景中谨慎使用。

推荐:


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peter-Lu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值