如果array = [1,2,3,4,5],我怎样才能将数字6,x的次数推到数组中.
array.push(6) * x
当我运行类似的东西时,它会返回被推送6次x的整个数组.将括号括在push * x周围会使我的代码无效,有什么建议吗?
例:
array.push(6) "2 times" => [1,5,6,6]
解决方法
是的,您可以使用
Array#fill
方法.
array = [1,5] array.fill(12,array.size,4) # => [1,12,12]
说明
Suppose you have an array
a = [1,3]
. Nowa.size
will give you3
,where last index is2
. So,when you are usinga.size
with#fill
,then you are telling to start pushing object from3
to somen
number of times.