在使用foreach循环时改变数组中的值

466

例子:

var arr = ["one","two","three"];

arr.forEach(function(part){
  part = "four";
  return "four";
})

alert(arr);

这个数组的值仍然是原来的,有没有办法从迭代函数中对数组元素进行写入访问?


1
相关:https://dev59.com/b1fUa4cB1Zd3GeqPH26g - Pacerier
5
尝试使用map方法(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map):`x=[2,3,4]; x=x.map(n=>n*2); // [4,6,8]` - Justin
11个回答

1
如果您想覆盖某个元素,可以尝试这个方法:

var newArray= [444,555,666];
var oldArray =[11,22,33];
oldArray.forEach((name, index) => oldArray [index] = newArray[index]);
console.log(newArray);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接