为什么我的forEach循环不编辑数组?

yoh*_*ver 2 javascript arrays

在课堂上,我以他们为例,介绍了使用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
Run Code Online (Sandbox Code Playgroud)

问题是,当我尝试使用相同的技术解决测验问题时,它不会更改数组的值。我认为这与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);
Run Code Online (Sandbox Code Playgroud)

我已经尝试过运行return语句,但是没有运气。我联系了他们的“实时帮助”,但他们的帮助不足。有人可以告诉我我在这里没看到吗?

kam*_*o94 5

forEach数组的方法不会修改数组,而只是对其进行迭代。当您在回调函数中更改参数时,这也不会影响数组。另外,forEach对回调的返回值不做任何事情。一旦计算出要替换的值,就可以使用index和array参数进行设置,就像这样。

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);
Run Code Online (Sandbox Code Playgroud)

  • 就目前而言,这个答案很好,但如果没有提到“地图”,则似乎很不完整。 (3认同)
  • 谢谢你。我认为这就是他们所要求的,但他们肯定不会事先解释任何这些。对此,我真的非常感激。 (2认同)

小智 5

您不会将每个值的引用传递到回调中,而只是传递该值。因此,您无需实际编辑数组即可更新本地值。

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

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