我有一个具有多行字符串的变量,我想将数组中的一些数据放在字符串的中间。我该怎么办?
var a = [1,2,3,4]
var b = `<div>
//array value here
<span>1</span>
<span>2</span>
...
</div>`
答案 0 :(得分:2)
您可以将表达式放在模板文字中:
const a = [1, 2, 3, 4];
const b = `<div>
//array value here
<span>${a[0]}</span>
<span>${a[1]}</span>
...
</div>`;
console.log(b);
甚至:
const a = [1, 2, 3, 4];
const b = `<div>
//array value here
${a.reduce((acc, v) => acc += `<span>${v}</span>`, '')}
</div>`;
console.log(b);