无法记录父项for for

时间:2017-05-14 01:48:16

标签: javascript loops for-loop console.log

JS代码

function generate(rectWidth, rectHeight, amount) {

// holds size
let size = {
    width: [],
    height: []
};

// holds colors
let colors = [];

for (var i = 0; i < amount; i++) {
    // generate size
    var width = Math.floor((Math.random() * rectWidth) + 1);
    var height = Math.floor((Math.random() * rectHeight) + 1);

    var r = Math.floor((Math.random() * 255) + 1);
    var g = Math.floor((Math.random() * 255) + 1);
    var b = Math.floor((Math.random() * 255) + 1);

    // add size to object
    size.width.push(width);
    size.height.push(height);
    colors.push(`rgb(${r}, ${g}, ${b})`);
}

return {
    size: size,
    colors: colors
};

};

let properties = generate(50, 50, 10);

for (let width = 0; width < properties.size.width.length; width++) {
        for (let height = 0; height < properties.size.height; height++) {
            for (let color = 0; color < properties.colors.length; color++) {

                console.log(properties.size.width[width]);

            }
        }
    }

问题

所以我的问题是在我的代码中我正在尝试console.log(properties.size.width[width]);,但它没有记录,而且我没有收到错误消息。

我想要发生什么

我希望我的代码console.log() properties.size.width

的值

我尝试了什么

  1. 我尝试在循环中使用var而不是let

1 个答案:

答案 0 :(得分:1)

for (let height = 0; height < properties.size.height; height++)应该是

for (let height = 0; height < properties.size.height.length; height++)

function generate(rectWidth, rectHeight, amount) {

// holds size
let size = {
    width: [],
    height: []
};

// holds colors
let colors = [];

for (var i = 0; i < amount; i++) {
    // generate size
    var width = Math.floor((Math.random() * rectWidth) + 1);
    var height = Math.floor((Math.random() * rectHeight) + 1);

    var r = Math.floor((Math.random() * 255) + 1);
    var g = Math.floor((Math.random() * 255) + 1);
    var b = Math.floor((Math.random() * 255) + 1);

    // add size to object
    size.width.push(width);
    size.height.push(height);
    colors.push(`rgb(${r}, ${g}, ${b})`);
}

return {
    size: size,
    colors: colors
};

};

let properties = generate(50, 50, 10);

for (let width = 0; width < properties.size.width.length; width++) {
        for (let height = 0; height < properties.size.height.length; height++) {
            for (let color = 0; color < properties.colors.length; color++) {

                console.log(properties.size.width[width]);

            }
        }
    }