2017-05-14 11 views
1

JS codeImpossible de se connecter valeur de parent boucle

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

      } 
     } 
    } 

Problème

Donc mon problème est que dans mon code, je suis en train de console.log(properties.size.width[width]);, mais ce ne est pas l'exploitation forestière, et je ne reçois pas de messages d'erreur.

Ce que je veux arriver

Je veux que mon code pour console.log() les valeurs de properties.size.width

Ce que j'ai essayé

  1. J'ai essayé d'utiliser var au lieu de let à l'intérieur de la boucle.

Répondre

1

for (let height = 0; height < properties.size.height; height++) devrait être

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

 
      } 
 
     } 
 
    }