Array.from使用场景:这些实用技巧你未必都知道

把类数组变成真数组

平时写网页时,经常遇到一些长得像数组但不是数组的东西,比如函数里的 arguments,或者用 document.querySelectorAll 拿到的 NodeList。它们能用下标访问,也有 length,偏偏不能直接用 map、filter 这些方法。

这时候 Array.from 就派上用场了。它能把这些“伪数组”转成真正的数组,立马就能调用各种数组方法。

function sum() {
  const args = Array.from(arguments);
  return args.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6

快速生成数字序列

想生成一个从 0 到 n 的数字列表?比如做日历组件要显示 1 到 31 天,或者做一个分页器需要页码。以前可能得写个 for 循环,现在一行代码搞定。

// 生成 0 到 9
const numbers = Array.from({ length: 10 }, (_, index) => index);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

这里的第二个参数是个映射函数,相当于在生成的同时执行 map 操作,效率更高。

复制并转换字符串为字符数组

字符串本身有 Symbol.iterator,也能被 Array.from 处理。比起 str.split(''),它更直观,还能顺便处理一些特殊字符。

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

// 包含 emoji 也没问题
const emojis = Array.from('👍👏😊');
// ['👍', '👏', '😊']

处理 DOM 节点集合

前端操作中,常会选中一组元素,比如所有复选框。querySelectorAll 返回的是 NodeList,虽然能遍历,但不能直接用 find 或 filter。

用 Array.from 转一下,马上就能流畅操作。

const checkboxes = Array.from(document.querySelectorAll('input[type="checkbox"]'));
const checkedOnes = checkboxes.filter(cb => cb.checked);
const values = checkedOnes.map(cb => cb.value);

结合 Set 去重并转数组

数据处理时,经常要对一串重复的值去重。Set 能做到,但返回的是集合。配合 Array.from,一步到位。

const list = [1, 2, 2, 3, 4, 4, 5];
const unique = Array.from(new Set(list));
// [1, 2, 3, 4, 5]

虽然现在有扩展运算符 [...new Set(list)],但 Array.from 更明确,兼容性也好一些,尤其在老项目里更稳妥。

创建固定长度的空数组并填充

有时候需要初始化一个指定长度的数组,每个位置都是某个默认值,比如画布网格、游戏地图。

// 创建 5x5 的空格子
const grid = Array.from({ length: 5 }, () => 
  Array.from({ length: 5 }, () => null)
);
// 一个 5 行 5 列的二维数组

这种方式比 new Array(5).fill() 更可靠,特别是嵌套时不会出现引用共享的问题。