gpt4 book ai didi

JavaScript 在模板字符串中返回超过 21 y/o 的 boolean 值

转载 作者:行者123 更新时间:2023-12-02 23:25:08 25 4
gpt4 key购买 nike

我不知道如何在模板字符串中实现大于公式以返回 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>

最佳答案

您的问题是不需要返回,因为您不在函数中。相反,由于您所需要的只是显示 truefalse,因此您只需使用 age > 20 的值即可:

const age = 47; // simplified for question
let html = `<ul>
<li>Alcohol allowed?: ${age > 20}</li>
</ul>`;

document.body.innerHTML = html;

或者,如果您想显示 truefalse 之外的其他值,则可以使用三元。

参见下面的示例:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com