在我正在学习的一个类中,它们给出了一个用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语句,但没有成功。我联系了他们的“现场帮助”,但他们对我没有多大帮助。有人能告诉我我在这里看不到什么吗?
发布于 2017-10-16 02:31:34
数组的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);
发布于 2017-10-16 02:38:26
不是将每个值的引用传递给回调,而是将值传递给回调。因此,您正在更新一个本地值,而不需要实际编辑数组。
您可以通过将索引传递给回调,然后编辑该索引的值来更新数组。
test.forEach(function(element,index){
if (element % 3 === 0){
test[index] = element + 100;
}
});发布于 2017-10-16 02:34:10
只要在数组上传递索引,它就会被修改。
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){
if (element % 3 === 0){
test[index] += 100;
}
});
console.log(test);https://stackoverflow.com/questions/46762112
复制相似问题