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
我尝试了什么
var
而不是let
。答案 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]);
}
}
}