HeresJohnny5 HeresJohnny5 - 4 months ago 8
Javascript Question

Results from loop don't work correctly


  1. I want to loop through an array.

  2. Any index which has a length larger than 3 I want to abbreviate.

  3. I want to place the new abbreviated months into a new array.

  4. I want to test that it works by writing the results to the console.



I can get the code to run, however the results don't come out the way I'd hope. From my understanding the loop runs true, running the if statement, which runs true, running the code block. After that the loop should iterate and continue as long as i < months.length, but it doesn't.



var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];

for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev = months[i].slice(0, 3);
}
}

console.log(monthsAbbrev);




Answer

You need to add the months to your monthsAbbrev array. One way you can do this is by using the .push() function:

var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];

for (var i = 0; i < months.length; i++) {
  if (months[i].length > 3) {
    monthsAbbrev.push(months[i].slice(0, 3));
  }
}

console.log(monthsAbbrev);