为什么我的forEach循环不编辑我的数组? [英] Why is my forEach loop not editing my array?

查看:69
本文介绍了为什么我的forEach循环不编辑我的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我上的一堂课中,他们给出了一个使用forEach()循环编辑数组内容的示例.

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

课程示例:

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语句有关,但是他们要求我们使用它,所以为什么他们不告诉我们存在问题?

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?

我的代码:

/*
 * 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语句,但是没有运气.我联系了他们的实时帮助",但他们的帮助不足.有人可以告诉我我在这里没看到吗?

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?

推荐答案

The forEach method of an array does not modify the array, it just iterates over it. When you change the argument in the callback function, that doesn't affect the array either. Also, forEach doesn't do anything with the return values from the callback. Once you calculate the value you want to use to replace, you can set it using the index and array arguments, like so.

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

这篇关于为什么我的forEach循环不编辑我的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆