javascript - 无法记录父 for 循环的值

标签 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

最佳答案

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]);

            }
        }
    }

关于javascript - 无法记录父 for 循环的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43959635/

相关文章:

javascript - 单击按钮时动态更新样式,D3 条形图

Java:如何循环三个List<String>

c - 如何创建输入循环?

python - 如何用另一个列表中的字典值填充一个列表中的字典值?

javascript - JavaScript 中键值对数组的求和值

javascript - 在单个循环中将字符串与数组的所有元素进行比较

javascript - 使用 javascript 的 3d 立方体形状

java - 我如何将这个 for every 转换为 for 循环?

c++ - 如何在使用for循环和数组时更改为c代码

javascript - 如何以json格式存储日期并在给定范围内一一显示它们?