用于初始化给定长度数组的模板文字

Template literals to initialize an array of given length

我遇到了 (如何初始化像 [{id: 1},{id: 2},...] 这样的数组)。

接受的答案是:

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

console.log(sampleData)

还有很多其他的。
但是,我想到了 template literals 作为解决方案,但我不知道如何让它发挥作用。

我目前拥有的是:

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

但是,它使用 eval,我知道这是错误的。

我也试过了

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

但我还没有以某种方式调用此字符串上的反引号(类似于 arr 上的 TemplateLiteralFunction.call)来解析这些表达式。
而不是编写标记函数,我只编写了一个名为 initArray(ofLength).

的函数

那么,是否可以使用不带 eval 的模板字面量或标记函数,并获得一个给定长度的数组,其中填充了值?也许以某种方式嵌套模板文字?

您可以使用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));