Javascript推送和循环[重复]

问题描述 投票:0回答:1

我目前有这样一个数组:var arr = []如何使用for循环将多个 "hello "字符串推入数组?

var newArray = arr.push("hello")10;
javascript arrays for-loop push
1个回答
0
投票

尝试newArray forEach 或简单的for-loop应该可以。

var arr = [];

// method 1
new Array(5).fill(0).forEach(() => arr.push("hello"));

// alternate method
for (let i = 0; i < 5; i++) {
  arr.push("world");
}

console.log(arr);

// Updating based on suggesion @mplungjan, quick way without loop.
var arr2 = Array(10).fill("hello");
console.log(arr2)
© www.soinside.com 2019 - 2024. All rights reserved.