0

I currently have this array: var arr = [] How do I push multiple "hello" strings into the array using a for loop? I tried

var newArray = arr.push("hello")10;
2

1 Answer 1

0

try new Array forEach or simple for-loop should work.

var arr = [];

// method 1
new Array(5).fill(0).forEach(() => arr.push("hello"));

// alternate method
for (let i = 0; i < 5; i++) {
  arr.push("world");
}

console.log(arr);

// Updating based on suggesion @mplungjan, quick way without loop.
var arr2 = Array(10).fill("hello");
console.log(arr2)

Sign up to request clarification or add additional context in comments.

3 Comments

var arr = new Array(10).fill("hello")
Oh right, Thanks @mplungjan. Just realising I think further short way is var arr = Array(10).fill("hello").

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.