Home > Back-end >  JS How to save the result of a for loop as an array?
JS How to save the result of a for loop as an array?

Time:12-18

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = [];

for (let i = 0; i < cars.length; i  ) {
  const i = 'hi';
  console.log(i);
}

the result of this code would be:

hi
hi
hi
hi
hi
hi

how can I save this result to a variable as an array? The returned value should be: ['hi','hi','hi','hi','hi','hi']

CodePudding user response:

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = [];
const x = 'hi';

for (let i = 0; i < cars.length; i  ) {
  arr.push(x);
}

CodePudding user response:

The best thing you can make use of is map operator

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = cars.map(car => 'hi');
  • Related