在我正在学习的课程中,他们给出了一个使用 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
语句但没有运气。我联系了他们的“实时帮助”,但他们的帮助不大。有人可以告诉我我在这里没有看到什么吗?
原文由 yohohosilver 发布,翻译遵循 CC BY-SA 4.0 许可协议
数组的
forEach
方法不修改数组,它只是迭代它。当您更改回调函数中的参数时,这也不会影响数组。此外,forEach
不对回调的返回值做任何事情。一旦计算出要用于替换的值,就可以使用索引和数组参数设置它,就像这样。