[英]Assign same value to multiple elements of array in JavaScript
Is possible to assign same value to multiple elements of array in JavaScript ?是否可以在 JavaScript 中为数组的多个元素分配相同的值?
If i have this array:如果我有这个数组:
var arr= [
[0,1],
[0,1],
[0,1]
];
Is possible to assign value 1
to arr[i][0]
for all elements having like output:对于所有具有类似输出的元素,可以将值
1
分配给arr[i][0]
:
[
[1,1],
[1,1],
[1,1],
[1,1]
]
This output without to use for loop ?此输出无需使用for 循环?
There are multiple ways of achieving this without a for
loop, however, Array.fill()
is probably easiest and modifies the array in place.有多种方法可以在没有
for
循环的情况下实现这一点,但是, Array.fill()
可能是最简单的,并且可以就地修改数组。
arr.fill([1,1])
Other methods like Array.map()
and Array.reduce()
will return a new array. Array.map()
和Array.reduce()
等其他方法将返回一个新数组。
您可以使用地图功能
arr = arr.map(x => [1, x[1]])
You can use map
for this as well您也可以为此使用
map
var res = [ [0,1], [0,1], [0,1] ].map(([d, ...rest]) => [1, ...rest]) console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.