【发布时间】: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