[英]Template literals to initialize an array of given length
I bumped into this question (how to init an array like [{id: 1},{id: 2},...]
). 我遇到了这个问题 (如何初始化像
[{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. 但是,它使用
eval
,我知道这是错误的。
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. 但我还没有以某种方式调用此字符串的后面的滴答(类似于
arr
TemplateLiteralFunction.call
)来解析这些表达式。
And instead of writting a tag function I'd just write a function called initArray(ofLength)
. 而不是写一个标记函数,我只是编写一个名为
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? 那么,有没有你可以使用模板文字而没有
eval
或tag函数,并实现一个给定长度的数组填充值? Perhaps somehow nesting template literals? 也许以某种方式嵌套模板文字?
You can use Function constructor 您可以使用Function构造函数
The Function constructor creates a new Function object.
Function构造函数创建一个新的Function对象。 Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues similar to eval.
直接调用构造函数可以动态创建函数,但是会遇到类似于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.
但是,与eval不同,Function构造函数允许在全局范围内执行代码,从而提示更好的编程习惯并允许更有效的代码缩小。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.