【问题标题】:forEach loop to assign new value to variables in array is not replacing value of variables [duplicate]为数组中的变量分配新值的forEach循环不会替换变量的值[重复]
【发布时间】:2026-01-04 14:35:01
【问题描述】:

我正在尝试使用 forEach 循环遍历包含三个变量的数组,并将每个变量的值更改为 0-255 之间的随机数。

我已经开始给每个变量一个简单的值:

let rgb1 = 1;
let rgb2 = 2;
let rgb3 = 3;

然后我将这些变量放入一个数组中:

let rgbVariables = [rgb1,rgb2,rgb3];

我的函数返回 0-255 之间的随机数

function randomColor() {
    return Math.floor((Math.random() * 255));
}

最后是我在数组上循环的函数

function refreshRGBNumbers() {
    rgbVariables.forEach(function(rgb) {
      rgb = randomColor();
    });

当我单击按钮时会调用 refreshRGBNumbers 函数。我已经验证该函数被正确调用,但是当我检查数组中变量的值时,它们仍然是 1,2,3。

我需要在这里做什么才能让函数正确地用随机数替换数组变量?

【问题讨论】:

  • rgbVariables.forEach(function(rgb) { rgb = randomColor(); }); 对数组没有任何作用,它不会改变值
  • 你不能改变原始值。做forEach((rgb, index, array) => array[index] = randomColor()) 或者更好.map(() => randomColor())

标签: javascript arrays


【解决方案1】:

如果你想改变数组中的值,你需要直接改变它。

rgbVariables.forEach(function(val, index, array) { array[index] = randomColor(); })

【讨论】:

  • 数组中的值是原始值,forEach 没有传递对数组元素的引用,它传递原始值
  • @epascarello 当我用你在那里的功能替换我的功能时,我遇到了同样的问题。新函数:function refreshRGBNumbers() { rgbVariables.forEach(function(val, index, array) { array[index] = randomColor(); }) console.log(rgb1); console.log(rgb2); console.log(rgb3); } 返回和之前一样的 1,2,3
  • 变量永远不会更新,这不是它的工作原理。
  • 当您将变量粘贴到数组中时,它并没有引用该变量,而是当时的值。
最近更新 更多