When I console.log
the array below, undefined
is a part of each array item, I would like to know why is that and how to get rid of it?
new_colors.addEventListener("click", function() {
var rgb_guesses = new Array();
for(var i = 0; i < color_squares.length; i++) {
var rgb_value = "rgb" + "(" + random() + "," + " " + random() + "," + " " + random() + ")";
color_squares[i].style.background = rgb_value;
rgb_guesses[i] += rgb_value;
}
guess_rgb.textContent = color_squares[3].style.background;
console.log(rgb_guesses);
});
You've created an empty array
So, the statement
rgb_guesses[i] += rgb_value;
is shorthand for
rgb_guesses[i] = rgb_guesses[i] + rgb_value;
Now as the array is empty, rgb_guesses[i]
will be undefined until you assign a value to it ... undefined when coerced to a string, is "undefined"
So, your code is doing the equivalent of
rgb_guesses[i] = "undefined" + rgb_value;
Since you are only ever assigning a single value to each element in the array, you can change your code to simply
rgb_guesses[i] = rgb_value;
Or
rgb_guesses.push(rgb_value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.