如何摆脱undefined?

时间:2018-02-08 23:12:41

标签: javascript undefined

当我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);
});

1 个答案:

答案 0 :(得分:1)

您已创建空数组

所以,声明

rgb_guesses[i] += rgb_value; 

的简写
rgb_guesses[i] = rgb_guesses[i] + rgb_value;

现在,当数组为空时,rgb_guesses[i]将是未定义的,直到您为其赋值... ...在强制转换为字符串时未定义,是&#34;未定义&#34;

所以,你的代码相当于

rgb_guesses[i] = "undefined" + rgb_value;

由于您只是为数组中的每个元素分配单个值,因此您可以将代码更改为

rgb_guesses[i] = rgb_value;

或者

rgb_guesses.push(rgb_value);