高级前端
js
【Q507】如何创建一个数组大小为100,每个值都为0的数组

如何创建一个数组大小为100,每个值都为0的数组

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 520 (opens in a new tab)

Author 回答者: janyin (opens in a new tab)

const arr = new Array(100); arr.fill(0)

Author 回答者: shfshanyue (opens in a new tab)

列举三种方法:

// 方法一:
Array(100).fill(0);
 
// 方法二:
// 注: 如果直接使用 map,会出现稀疏数组
Array.from(Array(100), (x) => 0);
 
// 方法二变体:
Array.from({ length: 100 }, (x) => 0);

Author 回答者: shfshanyue (opens in a new tab)

const arr = new Array(100); arr.fill(0)

可以省略 new 操作符,较为简洁