例子:

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

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

alert(arr);

数组仍然是它的原始值,有任何方法来写访问数组的元素从迭代函数?


当前回答

数组:[1,2,3,4] 结果:["foo1", "foo2", "foo3", "foo4"]

保持原始数组

const originalArr = ["Iron", "Super", "Ant", "Aqua"]; const modifiedArr = originalArr。Map (name => ' ${name}man '); console.log("Original: %s", originalArr); console.log("Modified: %s", modifiedArr);

覆盖原始数组

let originalArr =["铁","超级","蚂蚁","水"]; originalArr = originalArr。Map (name => ' ${name}man '); console.log("Original: %s", originalArr);

重写原始数组

const originalArr = ["Iron", "Super", "Ant", "Aqua"]; originalArr。forEach((name, index) => originalArr[index] = ' ${name}man '); console.log("被覆盖:%s", originalArr);

其他回答

将其替换为数组的索引。

array[index] = new_value;

要完全添加或删除会改变索引的元素,可以通过扩展zhujy_8833的slice()建议迭代一个副本,只需计算已经删除或添加的元素的数量,并相应地更改索引。例如,要删除元素:

let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
    if (value === "A2" || value === "A5") {
        values.splice(index - count++, 1);
    };
});
console.log(values);

// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]

在前面插入元素:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - count--, 0, 'newVal');
};

// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]

在后面插入元素:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - --count, 0, 'newVal');
};

// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']

替换一个元素:

if (value === "A3" || value === "A4" || value === "A7") {
    values.splice(index, 1, 'newVal');
};

// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]

注意:如果同时实现'before'和'after'插入,代码应该先处理'before'插入,否则就不会像预期的那样

回调函数传递元素、索引和数组本身。

arr.forEach(function(part, index, theArray) {
  theArray[index] = "hello world";
});

edit -正如注释中所指出的,.forEach()函数可以接受第二个参数,它将在每次调用回调时用作this的值:

arr.forEach(function(part, index) {
  this[index] = "hello world";
}, arr); // use arr as this

第二个例子显示了在回调中arr本身是这样设置的。有人可能会认为.forEach()调用中涉及的数组可能是this的默认值,但不管出于什么原因,它不是;如果没有提供第二个参数,则没有定义。

(注意:如果回调函数是=>函数,上述内容并不适用,因为在调用此类函数时,它从未绑定到任何东西。)

同样重要的是要记住,Array原型上提供了一整套类似的实用程序,并且Stackoverflow上出现了许多关于某个函数或另一个函数的问题,因此最好的解决方案就是选择一个不同的工具。你有:

forEach用于对数组中的每个条目执行操作; 用于生成只包含符合条件的项的新数组的过滤器; 映射,通过转换现有数组来创建一个一对一的新数组; 一些用于检查数组中是否至少有一个元素符合某些描述; each用于检查数组中的所有条目是否与描述匹配; Find用于在数组中查找值

等等。MDN链接

foreach函数可以有一个回调函数(eachelement, elementIndex) 所以基本上你需要做的是:

arr.forEach(function(element,index){
    arr[index] = "four";   //set the value  
});
console.log(arr); //the array has been overwritten.

或者,如果您想保留原始数组,可以在执行上述过程之前对其进行复制。 要制作副本,您可以使用:

var copy = arr.slice();

让我们尽量保持简单,并讨论它是如何实际工作的。它与变量类型和函数参数有关。

下面是我们正在讨论的代码:

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

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

alert(arr);

首先,这里是你应该阅读关于Array.prototype.forEach()的地方:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

其次,让我们简要地讨论一下JavaScript中的值类型。

基本类型(未定义,空,字符串,布尔,数字)存储一个实际值。

var x = 5;

引用类型(自定义对象)存储对象的内存位置。

例如:var xObj = {x: 5};

第三,函数参数是如何工作的。

在函数中,参数总是按值传递。

因为arr是一个字符串数组,它是一个基本对象数组,这意味着它们是按值存储的。

所以对于上面的代码,这意味着每次forEach()迭代时,part都等于arr[index]的相同值,但不是同一个对象。

Part = "four";改变部分变量,但不改变arr。

下面的代码将改变你想要的值:

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

arr.forEach(function(part, index) {
  arr[index] = "four";
});

alert(arr);

现在,如果数组arr是一个引用类型的数组,下面的代码将工作,因为引用类型存储的是对象的内存位置,而不是实际对象。

var arr = [{ num : "one" }, { num : "two"}, { num : "three"}];

arr.forEach(function(part, index) {
  // part and arr[index] point to the same object
  // so changing the object that part points to changes the object that arr[index] points to

  part.num = "four";
});

alert(arr[0].num);
alert(arr[1].num);
alert(arr[2].num);

下面的例子说明了你可以改变part来指向一个新的对象,同时保留存储在arr中的对象:

var arr = [{ num : "one" }, { num : "two"}, { num : "three"}];

arr.forEach(function(part, index) {
  // the following will not change the object that arr[index] points to because part now points at a new object
  part = 5;
});

alert(arr[0].num);
alert(arr[1].num);
alert(arr[2].num);