Why is my forEach loop not editing my array?

时间:2017-10-16 02:25:06

标签: javascript arrays

In a class I am taking they give an example of editing an Array's contents with a forEach() loop.

Classes Example:

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

The problem is when I try to solve a quiz problem using the same technique it doesn't change the arrays values. I believe this has to do with the if statement but they ask us to use it, so why would they not tell us there is an issue?

My Code:

/*
 * 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);

I have tried running return statements but no luck. I reached out to their "Live Help" but they were less than helpful. Can someone please tell me what I am not seeing here?

3 个答案:

答案 0 :(得分:2)

数组的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);

答案 1 :(得分:0)

只需传递数组上的索引然后就会被修改。

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);

答案 2 :(得分:0)

您没有将每个值的引用传递给回调,只是值。因此,您无需实际编辑阵列即可更新本地值。

您可以通过将索引传递给回调,然后编辑该索引处的值来更新数组。

test.forEach(function(element,index){ 
    if (element % 3 === 0){ 
        test[index] = element + 100; 
    } 
});