0
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']

3
  • 1
    Add arr.push(i) to the loop. Commented Dec 17, 2021 at 18:58
  • 1
    Why are you declaring i inside the loop with the same name as the loop counter? What if you needed the value of the loop counter inside the loop? Commented Dec 17, 2021 at 19:11
  • (new Array(cars.length)).fill('hi') Commented Dec 17, 2021 at 19:34

3 Answers 3

1
const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi']; const arr = []; const x = 'hi'; for (let i = 0; i < cars.length; i++) { arr.push(x); } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Also [...cars].fill('hi')
0

Another option using Array.from()

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi']; const arr = Array.from(cars, _ => "hi"); 

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi']; const arr = Array.from(cars, _ => "hi"); console.log(arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.