返回

用Array.from让JS代码更简洁易读

前端

揭秘 Array.from 方法:从字符串到数组的转换秘籍

前言

在 JavaScript 的广阔世界中,数组扮演着至关重要的角色,充当着存储和操纵数据的容器。而创建数组的传统方式,如 Array() 函数和方括号 ([]),虽然简单好用,但在某些情况下,它们却显得有些笨重。此时,Array.from 方法横空出世,以其简洁性和灵活性,为我们提供了另一种创建数组的途径。

Array.from 方法概述

Array.from 方法的作用,顾名思义,就是将一个字符串、类数组对象或可迭代对象转化为一个数组。它的语法如下:

Array.from(iterable[, mapFn[, thisArg]])

其中,

  • iterable :要转换的字符串、类数组对象或可迭代对象。
  • mapFn :可选。一个映射函数,用于对数组中的每个元素进行映射。
  • thisArg :可选。一个值,作为 mapFn 函数的 this 值。

Array.from 方法的使用场景

将字符串转换为数组

Array.from 方法可以轻松地将字符串转换为一个包含字符串中每个字符的数组,例如:

const str = 'Hello World';
const arr = Array.from(str);

console.log(arr); // ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

将类数组对象转换为数组

类数组对象指的是那些具有 length 属性且可以用索引访问元素的对象,例如 NodeList、HTMLCollection 和 Arguments 对象。Array.from 方法可以将这些类数组对象转换为真正的数组,例如:

const nodes = document.querySelectorAll('li');
const arr = Array.from(nodes);

console.log(arr); // [<li>...</li>, <li>...</li>, ...]

将可迭代对象转换为数组

可迭代对象指的是可以被遍历的对象,例如字符串、数组和 Set 对象。Array.from 方法可以将这些可迭代对象转换为数组,例如:

const set = new Set([1, 2, 3, 4, 5]);
const arr = Array.from(set);

console.log(arr); // [1, 2, 3, 4, 5]

使用 mapFn 函数映射数组元素

在调用 Array.from 方法时,可以传入一个 mapFn 函数,对数组中的每个元素进行映射。mapFn 函数接收两个参数:

  • element:数组中的元素
  • index:元素的索引

mapFn 函数可以返回任何值,这些值将作为新数组的元素。例如,以下代码使用 mapFn 函数将数组中的每个元素加 1:

const arr = [1, 2, 3, 4, 5];
const newArr = Array.from(arr, (element) => element + 1);

console.log(newArr); // [2, 3, 4, 5, 6]

Array.from 方法与其他数组创建方法的比较

在 JavaScript 中,除了 Array.from 方法,还有其他几种创建数组的方法,包括 Array() 函数、方括号 ([]) 和字面量 ([]=)。下表比较了这些方法的优缺点:

方法 优点 缺点
Array() 函数 简单易用 创建空数组时效率较低
方括号 ([]) 简单易用 不能将字符串或类数组对象转换为数组
字面量 ([]=) 创建数组时效率较高 不能将字符串或类数组对象转换为数组
Array.from 方法 可以将字符串、类数组对象或可迭代对象转换为数组 比其他方法复杂

结论

Array.from 方法是一种功能强大且灵活的数组创建工具,它可以轻松地将各种数据结构转换为数组。相比于其他数组创建方法,Array.from 方法提供了更多的灵活性,使其成为复杂数据操作场景中的首选。

常见问题解答

  1. Array.from 方法可以转换哪些类型的对象?

Array.from 方法可以转换字符串、类数组对象和可迭代对象。

  1. Array.from 方法的复杂度是多少?

Array.from 方法的时间复杂度为 O(n),其中 n 是可迭代对象的长度。

  1. mapFn 函数中的 thisArg 参数有什么作用?

thisArg 参数指定了 mapFn 函数的 this 值。

  1. Array.from 方法可以接受多个可迭代对象吗?

不可以,Array.from 方法只能接受一个可迭代对象作为参数。

  1. Array.from 方法与 for...of 循环有什么区别?

Array.from 方法会立即创建数组,而 for...of 循环则会按需生成数组的元素。