Javascript push and loop



我目前有这个数组:var arr = [] 如何使用 for 循环将多个"hello"字符串推送到数组中? 我试过了

var newArray = arr.push("hello")10;

尝试新的数组forEach或简单的for循环应该可以工作。

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)

最新更新