0

I'm trying to loop over an array that contains three variables with a forEach loop, and change the value of each variable to a random number between 0-255.

I've started out by giving each variable a simple value:

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

And then I've put those variables into an Array:

let rgbVariables = [rgb1,rgb2,rgb3];

I have my function that returns a random number between 0-255

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

And lastly my function that loops over the array

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

The refreshRGBNumbers function is called when I click a button. I have verified that the function is being called correctly, but when I check the value of the variables in the array they remain 1,2,3.

What do I need to do here to get the function to correctly replace the array variables with the random number?

NickC
  • 332
  • 1
  • 15
  • `rgbVariables.forEach(function(rgb) { rgb = randomColor(); });` does nothing to the array, It does not alter the value – epascarello Oct 11 '19 at 19:04
  • 2
    You can't mutate primitive values. Do `forEach((rgb, index, array) => array[index] = randomColor())` or better yet `.map(() => randomColor())` – VLAZ Oct 11 '19 at 19:06

1 Answers1

1

If you want to alter the values in the array, you would need to alter it directly.

rgbVariables.forEach(function(val, index, array) { array[index] = randomColor(); })
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • The values in your are array are primitives, the forEach isn't passing a reference to the array element, it passes the primitive value – Ted Fitzpatrick Oct 11 '19 at 19:14
  • @epascarello when I replace my function with what you have there I have the same issue. New function: ```function refreshRGBNumbers() { rgbVariables.forEach(function(val, index, array) { array[index] = randomColor(); }) console.log(rgb1); console.log(rgb2); console.log(rgb3); }``` Returns the same 1,2,3 as before – NickC Oct 11 '19 at 19:17
  • 1
    The variables will never update, that is not how it works. – epascarello Oct 11 '19 at 19:19
  • 1
    When you stick the variable in the array it is not referencing that variable, it is that value at that time. – epascarello Oct 11 '19 at 19:24