JavaScript中,如果创建重复的元素, 原问题: https://stackoverflow.com/questions/12503146/create-an-array-with-same-element-repeated-multiple-times
下面的场景是创建一个数组,数组里包含5
个重复的元素2
:
Array.from
Array.from({ length: 5 }).map(x => 2)
Array.from({ length: 5 }, i => 2)
Array.from({ length: 5 }, (e, i) => i) // => 0, 1, 2, 3, 4
fill
Array(5).fill(2)
Array.apply
Array.apply(null, Array(5)).map(() => 2)
Expand
[...Array(5)].map(() => 2)
join + split
Array(5).join("2").split("")
flat
Array(3).fill(['a','b','c']).flat() // => Array(9) [ "a", "b", "c", "a", "b", "c", "a", "b", "c" ]