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

For loop

I want to add an increment 0f 1 to each of the following in this array var kittenPiles = [3, 5, 7, 12];. How would I do this with a for loop?

right now I have...

var kittenPiles = [3, 5, 7, 12];
for(var i = 0, l = kittenPiles.length; i < l; i++){
    console.log(kittenPiles[i]);
}

Thanks.

2 Answers

//So, my understanding is that you want to increment each value in the array by one?
//Output to be: [ 4, 6, 8, 13 ] in the case.
var kittenPiles = [3, 5, 7, 12];
console.log(kittenPiles);
for(var i = 0; i < kittenPiles.length; i++) {
    kittenPiles[i] = kittenPiles[i] + 1;
}
console.log(kittenPiles);

Or simply:

var kittenPiles = [3, 5, 7, 12];
for(var i = 0, len = kittenPiles.length; i < len; i++) {
    kittenPiles[i]++;
}

Lol or:

var kittenPiles = [3, 5, 7, 12];
for(var i = 0; i < kittenPiles.length; ++i) {
    ++kittenPiles[i];
}

Thanks guys...