js for循环包含对象的数组templateLis
时间: 2023-10-10 19:06:33 浏览: 39
假设 `templateList` 是一个包含多个对象的数组,每个对象都包含一个模板字符串和一个数据对象,那么可以使用 for 循环遍历数组中的每一个对象,将其模板字符串编译成最终的 HTML 字符串。例如:
```
const templateList = [
{ template: "<p>Hello, ${name}!</p>", data: { name: "Alice" } },
{ template: "<p>Welcome to ${city}!</p>", data: { city: "New York" } },
{ template: "<p>Today is ${day}.</p>", data: { day: "Monday" } },
];
for (let i = 0; i < templateList.length; i++) {
const item = templateList[i];
const compiled = item.template.replace(/\${(\w+)}/g, (match, p1) => item.data[p1]);
console.log(compiled);
}
```
上述代码中,我们通过 for 循环遍历 `templateList` 数组,并将每一个对象 `item` 的模板字符串 `template` 编译成最终的 HTML 字符串 `compiled`。在编译的过程中,我们使用正则表达式 `/(\${\w+})/g` 匹配模板字符串中的占位符 `${}`,并使用 `replace()` 方法将其替换为相应的数据项。最后,我们将编译后的 HTML 字符串输出到控制台。这样,我们就可以通过遍历数组来处理其中的每一个对象。