Javascript 在 forEach 中使用 if 语句更改变量

Javascript changing variable with if statement in forEach

*使用现有的test变量并写一个forEach循环 * 每个能被 3 整除的数加 100。 * * 注意事项: * - 您必须使用 if 语句来验证代码是否可以被 3

整除

我很困惑,为什么我的代码不起作用?

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(number) {
if (number % 3 === 0) {
    number += 100;

});


console.log(test[0]); **this is returning 12, NOT the desired 112**

您没有将数字放回数组中。

基元不是引用。需要用到索引放回去

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

您需要在 for-each 循环中包含索引。并使用该索引更改实际数组中的值。

工作代码:

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(number, i) {
if (number % 3 === 0) {
    test[i] += 100;

}
});


console.log(test[0]); //print 112

正如其他人所说,您需要将读取数字的索引设置为值+100

Javascript 有很多不那么直观的怪癖,函数参数不遗余力。查看这篇文章,了解有关 Javascript 如何将 values/references 传递给函数的更多详细信息:

您可以使用 forEach() 的第三个参数编写一个不需要访问其范围的函数,就像这里的其他一些答案一样:

arr.forEach(function callback(currentValue, index, array) { ...

let 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 (number, index, array) {
  if (number % 3 === 0) {
    array[index] = number + 100
  }
})

console.log(test[0])

你可以使用forloop/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 ];

foreach

foreach (int i in test)
{
    if (i % 3 === 0) {
         i += 100;
     }
}

forloop

for (i = 0; i < test.Count; i++)
{
     if (test[i] % 3 === 0) {
         test[i] += 100;
     }
}