Reputation: 456
I have this var let number = 3
I'd like to create an array with the length based on the number listed above, But the content should be a string like this:
"item {index of item in array}",
so my array should look like this: let array = ['item 0', 'item 1', 'item 2']
Righ now I have this code:
let number = 2
let array = Array.from(Array(number).keys())
// outcome --> [ 0 , 1 ]
But I don't know how to add the strings in a correct way
Upvotes: 1
Views: 101
Reputation: 281
You can try this.
let number = 2;
let array = Array(number).fill().map((ele, i) => `item ${i}`);
Upvotes: 0
Reputation: 875
You can use this solution
let arr = [...Array(number).keys()].map(x=>`item ${x}`);
or
let arr = [...Array(number)].map((y, x)=>`item ${x}`);
Upvotes: 1
Reputation: 191976
Array.from()
accepts a callback, and you can use it to create the items.
const number = 2
const array = Array.from(Array(number).keys(), k => `item ${k}`)
console.log(array)
In addition, you can use the index (i
) of the item as the counter.
const number = 2
const array = Array.from(Array(number), (_, i) => `item ${i}`)
console.log(array)
Upvotes: 2