Array.push() replaces array elements with last element in a loop
I’m trying to generate tints of a color. So far, I have a function hexToRGB(hex)
that converts hex strings to arrays of form [r,g,b]
, and a function mix(f, a, b)
, that interpolates between two colors a
and b
in the ratio f
. These two functions work perfectly. However, when looping to generate tints using the following code, the array tints
always ends up filled with the last item, in this case [255,255,255]
.
document.querySelector("#colorpicker").addEventListener('change', e => {
const color = hexToRGB(e.target.value), n = document.querySelector('#range').value;
let tints = [];
for (let i=1; i<=n; i++) {
tints.push(mix(i/n, color, [255,255,255]));
}
console.log(tints);
});
// Output for n=3
// [[255,255,255],[255,255,255], [255,255,255]]
I tried logging the values to console to see if there was some problem with the for-loop output, but the issue lies in the array.push()
statement. I also did not store loop output in a variable to avoid storing object references, but this did not fix the issue.