首页 > 解决方案 > 了解 javascript 中 forEach 函数语句中的语法

问题描述

我现在正在使用 forEach 语句,这里有一段代码可以成功执行我正在处理的内容,但我不理解一个特定的语句。这段代码不是我写的。

let test = [10, 12, 14, 15, 16, 18];

test.forEach(function(num, index, array) {
  if (num % 3 === 0) {
    array[index] = num += 100; // <- This is the line of code that I am confounded by
  }
});
console.log(test);

我只是不明白它背后的逻辑。

抱歉,如果问题措辞不佳,这是我发布的第一个与编码相关的问题,感谢您的帮助。

标签: javascriptarraysforeach

解决方案


这是您正在寻找的解决方案:

array[index] = num += 100;不觉得很奇怪。

首先num += 100是在当前数字上加 100,最后将其分配给array[index]

以下是您的代码的简化版本

let test = [10, 12, 14, 15, 16, 18];

test.forEach(function(num, index, array) {
  if (num % 3 === 0) {
    num = num + 100;    // Adding 100 to old value (identical to num += 100)
    array[index] = num; // I do't think this is a weird code now
  }
});
console.log(test);

希望这会有所帮助谢谢......


推荐阅读