首页 > 解决方案 > How do you declare an array using an initializer list in javascript?

问题描述

creating the array would be this:

final int SIZE = 15, MULTIPLE = 10;

int [] list = new int [SIZE];

however, would this be the correct way to initialize the array?

for (int index = 0; index < SIZE; index++)
      list [index] = index * MULTIPLE;

标签: javascriptarraysarraylist

解决方案


Javascript 很奇怪(标准 js)。您可以初始化一个新数组,使用new Array(10)它创建一个长度为 10 但具有空值的新数组。因此,您不能迭代或映射数组或使用这些值。

数组上有一个.fill函数,如果将其与 Array(10) 结合使用,则会创建一个带有值的具有一定长度的数组。

然后,您可以使用for或更多 javascript 惯用的为什么map将索引值与您的乘数进行映射。

const SIZE = 15, MULTIPLE = 10;
const tmpArray = new Array(SIZE)
const initalArray = tmpArray.fill(0).map((value, i) => (i * MULTIPLE))

console.log(initalArray)


推荐阅读