[英]How to get rid of undefined?
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?当我
console.log
下面的数组时, undefined
是每个数组项的一部分,我想知道为什么会这样以及如何摆脱它?
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"现在由于数组为空,
rgb_guesses[i]
将是未定义的,直到您为其分配一个值... 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.