这个问题在这里已经有了答案:
change values in array when doing foreach
(11 个回答)
4年前关闭。
在我正在类的类(class)中,他们给出了一个使用 forEach()
编辑数组内容的示例。环形。
类示例:
var donuts = ["jelly donut", "chocolate donut", "glazed donut"];
donuts.forEach(function(donut) {
donut += " hole";
donut = donut.toUpperCase();
console.log(donut);
});
Prints:
JELLY DONUT HOLE
CHOCOLATE DONUT HOLE
GLAZED DONUT HOLE
问题是当我尝试使用相同的技术解决测验问题时,它不会更改数组值。我相信这与
if
有关声明,但他们要求我们使用它,那么他们为什么不告诉我们有问题呢?我的代码:
/*
* Programming Quiz: Another Type of Loop (6-8)
*
* Use the existing `test` variable and write a `forEach` loop
* that adds 100 to each number that is divisible by 3.
*
* Things to note:
* - you must use an `if` statement to verify code is divisible by 3
* - you can use `console.log` to verify the `test` variable when you're finished looping
*/
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139
];
test.forEach(function(element){
if (element % 3 === 0){
element += 100;
return element
}
});
console.log(test);
我试过运行
return
声明,但没有运气。我联系了他们的“实时帮助”,但他们的帮助不大。有人可以告诉我我在这里看不到什么吗?
最佳答案
forEach
数组的方法不会修改数组,它只是迭代它。当您更改回调函数中的参数时,这也不会影响数组。另外,forEach
不对回调的返回值做任何事情。一旦计算出要用于替换的值,就可以使用索引和数组参数来设置它,就像这样。
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139
];
test.forEach(function(element, index, array){
if (element % 3 === 0){
element += 100;
array[index] = element;
}
});
console.log(test);
关于javascript - 为什么我的 forEach 循环没有编辑我的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762112/