简体   繁体   中英

Template literals to initialize an array of given length

I bumped into this question (how to init an array like [{id: 1},{id: 2},...] ).

Accepted answer is:

 let sampleData = Array.from({length: 10}, (_, i) => ({id:i})) console.log(sampleData) 

And there are plenty others.
However, I thought of template literals as a solution, but I can't figure out how to make it work.

What I have so far is:

 var i = 0; var arr = `[${"{id:++i},".repeat(10)}]` console.log("As a string",arr); console.log("Evaluated",eval(arr)); 

However, it uses eval which I know it's wrong.

I also tried

 var i = 0; var arr = `[${"{id:${++i}},".repeat(10)}]` console.log(arr); 

But I have yet to somehow call the back ticks on this string (something like TemplateLiteralFunction.call on arr ), to parse those expressions.
And instead of writting a tag function I'd just write a function called initArray(ofLength) .

So, is there anyway you can use template literals without eval or tag functions and achieve an array of a given length filled with values? Perhaps somehow nesting template literals?

You can use Function constructor

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues similar to eval. However, unlike eval, the Function constructor allows executing code in the global scope, prompting better programming habits and allowing for more efficient code minification.

 var template = `[${"{\\"id\\":${++i}},".repeat(10)}]` template = template.replace(/,]$/,']'); //replace last comma var parser = new Function("{i}", "return `" + template + "`;"); var arr = parser({i:0}); console.log(JSON.parse(arr)); 

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