简体   繁体   中英

Create array with the length based on a number

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

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)

You can use this solution

let arr = [...Array(number).keys()].map(x=>`item ${x}`);

or

let arr = [...Array(number)].map((y, x)=>`item ${x}`);

You can try this.

let number = 2;
let array = Array(number).fill().map((ele, i) => `item ${i}`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM