简体   繁体   English

根据数字创建长度的数组

[英]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.

相关问题 创建手风琴的数组长度数 - Create array length number of Accordions 创建一个正则表达式以从列表中创建一个干净的数组,根据每个数字的长度对其进行过滤并检查其有效性(长度是否小于 4) - Create a regex for create a clean array from a list, filter it based on a length of each number and check its validity(whether length is less that 4) 如何根据长度不同的多个数组创建新的设定长度数组,以及根据重要性从每个较小的数组中取出的项目数 - How to create a new array of set length from multiple arrays of varying length, the number of items taken from each smaller arrays based on importance javascript根据另一个更大的数组创建具有固定长度的对象数组 - javascript create array of objects with a fixed length based on another bigger array JavaScript根据列表长度创建适当的行数和列数 - JavaScript create appropriate number of rows and columns based off of list length Javascript:根据每个数组的长度数对数组进行排序 - Javascript: Sort arrays based on each array's length number 如何创建一个 <ul> 根据数组编号 - How to create a <ul> based on an array number 根据 html 元素的数量创建数组 - create array based on number of html elements 根据数组长度,使用javascript创建concat字符串 - Based on array length create a concat string using javascript 如何根据JS中的数字编号从数字创建数组? - How to create array from number, based on digits number in JS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM