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
3 Answers
Reset to default 12Try 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
版权声明:本文标题:JavaScript generate array of strings with inline solution - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738705712a2107899.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论