[英]Create array with the length based on a number
I have this var let number = 3
我有这个 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']
所以我的数组应该是这样的: 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. Array.from()
接受回调,您可以使用它来创建项目。
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.此外,您可以使用项目的索引 ( i
) 作为计数器。
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}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.