Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge

Anthony Piscocama
Anthony Piscocama
4,328 Points

different approach

var html = '';

var color = ['red','green','blue']

var rgbColor;

for(var i = 0; i<= 3; i++){

     color[i] = Math.floor(Math.random() * 256 );

     rgbColor = 'rgb(color)';

     html += '<div style="background-color:' + rgbColor + '"></div>';

}

document.write(html);

i got the answer already but was messing around with this, is there anyway to get this to work? or why it wouldnt?

1 Answer

Using the video workspace the following will produce 3 colored circles:

var html = '';
var color = [0,0,0];
var rgbColor;

for(var i = 0; i < color.length; i++){
     color[i] = Math.floor(Math.random() * 256 );
     rgbColor = 'rgb(' + color + ')';
     html += '<div style="background-color:' + rgbColor + '"></div>';
}

document.write(html);

Some differences:

  • color is initialized with numbers instead of strings
  • the condition to run was changed to i < color.length. i <= 3 will result in a color with 4 parameters on the final iteration
  • color is concatenated in the assignment to rgbColor. Otherwise your color is the string 'rgb(color)'