Home > Software design >  Javascritpt - Looping through an array
Javascritpt - Looping through an array

Time:02-11

So i just started learning js and i can't solve this excercise:

Create a file named looping-through-arrays.js.

In that file, define a variable named pets that references this array:

['cat', 'dog', 'rat']

Create a for loop that changes each string in the array so that they are plural.

You will use a statement like this inside the for loop:

pets[i] = pets[i] 's'

I tried something like this code but apparently it doesn't work:

let pets = ["cat", "dog", "rat"];
for(let i = 0; i <= pets.length; i  ){
  pets[i] = pets[i]   "s";
};
console.log(pets);

CodePudding user response:

//Try this one   
 let pets = ["cat", "dog", "rat"];
    for(let i = 0; i < pets.length; i  ){
      pets[i] = pets[i]   "s";
    };
    console.log(pets);

CodePudding user response:

The error is that you are iterating including the length index of the array when using <=:

for(let i = 0; i <= pets.length; i  ){

So, since array indexing starts from 0, you should iterate up to the length without including it using only <.

Always remember that the last valid index of an array is equal to the length - 1.

  • Related