我不知道如何在模板字符串中实现大于公式以返回 boolean 值(请参阅代码)。
const age = 47; // simplified for question
let html;
html = `<ul>
<li>Alcohol allowed?: ${if (age > 20) {return 'true'} else {return 'false'}}</li>
</ul>`;
document.getElementById("replace").innerHTML = html;
<html>
<body>
<ul>
<li>Alcohol allowed?: true/false</li>
</ul>
</body>
</html>
最佳答案
您的问题是不需要返回
,因为您不在函数中。相反,由于您所需要的只是显示 true
或 false
,因此您只需使用 age > 20
的值即可:
const age = 47; // simplified for question
let html = `<ul>
<li>Alcohol allowed?: ${age > 20}</li>
</ul>`;
document.body.innerHTML = html;
或者,如果您想显示 true
或 false
之外的其他值,则可以使用三元。
参见下面的示例:
const age = 47; // simplified for question
let html = `<ul>
<li>Alcohol allowed?: ${age > 20 ? 'Above' : 'Below'}</li>
</ul>`;
document.body.innerHTML = html;
您可以阅读有关 conditional (ternary) operator 的更多信息在这里。
关于JavaScript 在模板字符串中返回超过 21 y/o 的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56772958/