admin管理员组

文章数量:1208153

There simple code:

var arr = [];
for(var i = 0; i < 10; i++){
    arr.push("some string with iterating value "+i);
}

I wonder if there is a one-line solution in which I enter the string and the maximum value and get an array of generated lines.

There simple code:

var arr = [];
for(var i = 0; i < 10; i++){
    arr.push("some string with iterating value "+i);
}

I wonder if there is a one-line solution in which I enter the string and the maximum value and get an array of generated lines.

Share Improve this question asked Oct 14, 2017 at 9:44 el paxel pax 1271 gold badge2 silver badges8 bronze badges 2
  • You want an array of strings in a one liner? – putvande Commented Oct 14, 2017 at 9:46
  • Let's say I have string: "some string %d" (%d is example). And maximum value: 2. I want to get array: ["some string 1", "some string 2"] – el pax Commented Oct 14, 2017 at 9:49
Add a comment  | 

3 Answers 3

Reset to default 12

Try this, if the input is 5, you can have it as N and get the input from user

DEMO

var result = Array.from(new Array(5),(val,index)=> "some string " + index );
console.log(result);

const newArray = [...Array(10)].map((_, i) => `some string with iterating value ${i}`)
console.log(newArray)

You can use a spread operator and create a new array of the length you require, loop (map) over it and return the string. This will create a new array of the length (10) with the string you want in it.

How about making it a reusable function? E.g.

// Replaces '{i}' with the index number
var generateStringArray = (length, string) => Array.from(new Array(length), (val, index) => string.replace('{i}', index))

console.log(generateStringArray(6, "some string {i}"));

本文标签: JavaScript generate array of strings with inline solutionStack Overflow