使用 Spread 将 Iterable 转换为数组 使用 Spread 将 Iterable 转换为数组

2025-06-10

使用 Spread 将 Iterable 转换为数组

使用 Spread 将 Iterables 转换为数组

使用 Spread 将 Iterables 转换为数组

SamanthaMing.com 的 CodeTidbit

使用 ES6 的 Spread(...) 轻松将可迭代对象转换为数组!通常,可迭代对象的内置方法有限。将其转换为数组后,您就可以使用所有强大的数组方法,例如 filter、map、reduce!太棒了🎉

[ ...'hi' ]; // // ['h', 'i']

[ ...new Set([1,2,3]) ]; // [1,2,3]

[ ...new Map([[1, 'one']]) ]; // [[1, 'one']]

[ ...document.querySelectorAll('div') ] // [ div, div, div]

内置可迭代对象

在 JavaScript 中,我们有一些内置的可迭代对象,我们使用Spread将它们转换为数组:

  • 细绳
  • 大批
  • 地图

还有一个,但本文我们不会重点讨论它TypedArray

什么是可迭代对象?

可迭代数据结构提供了一种机制,允许其他数据消费者以顺序方式公开访问其元素。

如果您有兴趣了解有关可迭代对象的更多信息,请查看这些精彩的帖子:

字符串 → 数组

const myString = 'hello';

const array = [...myString] // [ 'h', 'e', 'l', 'l', 'o' ]

我们可以使用以下方法将数组转换回字符串join()

array.join(''); // 'hello'

集合 → 数组

const mySet = new Set([1, 2, 3]);

const array = [...mySet] // [1, 2, 3]

我们可以通过将数组传递到new Set

new Set(array); // Set { 1, 2, 3 }

映射 → 数组

const myMap = new Map([[1, 'one'], [2, 'two']]);

const array = [...myMap] // [ [ 1, 'one' ], [ 2, 'two' ] ]

Set类似,我们可以通过将数组传递给new Map

new Map(array); // Map { 1 => 'one', 2 => 'two' }

节点列表 → 数组

const nodeList = document.querySelectorAll('div');

const array = [ ...document.querySelectorAll('div') ];
// [ div, div, div] *

*我建议您将代码粘贴到浏览器中以查看实际输出

Array.from 与 Spread

另一个与 Spread 语法非常相似的方法是Array.from。事实上,我们可以用这个来替换我们的例子:

Array.from('hi') // // ['h', 'i']

Array.from(new Set([1,2,3])) // [1,2,3]

Array.from(new Map([[1, 'one']])) // [[1, 'one']]

Array.from(document.querySelectorAll('div')) // [ div, div, div]

有什么区别?

区别在于定义

Array.from适用于:

  • 类似数组的对象(具有长度属性和索引元素的对象)
  • 可迭代对象

Spread仅适用于:

  • 可迭代对象

那么让我们看一下这个类似数组的对象:

const arrayLikeObject = {
  0: 'a', // indexed element
  1: 'b', // indexed element
  length: 1, // length property
};

// ✅ Using Array.from
Array.from(arrayLikeObject); // [ 'a', 'b' ]

// ❌ Using Spread
[...arrayLikeObject]; // TypeError: arrayLikeObject is not iterable

我应该使用哪一个?

当然,这得看情况。如果你使用的是类数组对象,你别无选择,只能使用Array.from。但说到可迭代对象,我一直都用。为什么?因为我是Airbnb 风格指南spreads的忠实粉丝。我希望有更好的理由,但这就是我所能给出的了,哈哈 😝 我猜是因为这样可以减少打字次数 🤔 如果你知道原因,请在评论中留言 😆

社区意见

@nickytonline我也喜欢使用 spread,但如果你想把 NodeList 转换为数组,然后对其进行 map 操作,可以考虑使用 Array.from。今年夏天我发现 Array.from 有第二个参数,它是一个 map 回调函数,在创建每个元素时都会调用。

资源


感谢阅读❤
打个招呼!Instagram | Twitter | Facebook |博客| SamanthaMing.com

鏂囩珷鏉ユ簮锛�https://dev.to/samanthaming/convert-iterable-to-array-using-spread-3o4o
PREV
CSS :not 选择器
NEXT
CodeRecipe:如何在 JavaScript 中反转数组