代码之家  ›  专栏  ›  技术社区  ›  boosted_duck

Array.from({length:5})和Array(5.fill(未定义)之间的区别是什么?

  •  -3
  • boosted_duck  · 技术社区  · 6 年前

    有什么区别:

    Array.from({length: 5})
    

    Array(5).fill(undefined)
    

    我可以看到两个方法都在创建一个数组 undefined 价值观。

    但我不明白他们的区别。

    2 回复  |  直到 6 年前
        1
  •  1
  •   GenericUser    6 年前

    它们有不同的用例。 Array.from 例如,对于某些返回类似于数组的对象的DOM方法是有用的,但没有任何数组方法。主要是把数组类的东西转换成 Array .

    const children = document.getElementById('container').children;
    console.log(children);
    
    const childrenArray = Array.from(children);
    console.log(childrenArray)
    <div id="container">
      <div>Block 1</div>
      <div>Block 2</div>
      <div>Block 3</div>
      <div>Block 4</div>
    </div>

    Array.fill 如果您有一些已知大小的数组并希望用某个值填充它,则更简单。

        2
  •  0
  •   Pasan Chamikara    6 年前

    数组()。 from ()返回未定义的值,因为它没有为数组索引指定特定值。

    事实与 Array(5).fill(<some_value>) 很明显。因为它总是填充相同的值直到数组的长度(在您的情况下,它是未定义的)