Ad

Javascritpt - Looping Through An Array

- 1 answer

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

Answer

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