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

标签 javascript boolean template-strings

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

相关文章:

javascript - 通过 HTML5 Canvas Context 缩放并在给定图像上绘制网格

JSON 提供者 jackson 使用 boolean 类型序列化和反序列化的问题

javascript - If Else 条件在 Javascript 模板文字中不起作用

javascript - Laravel 和 Ajax : Send specific url to get data?

javascript - JQuery .load() 没有添加到 DOM?

javascript - 处理非 Angular 代码时如何立即更新 $scope?

javascript - 不能在 node.js 中使用模板字符串

转换到 _Bool

algorithm - 从 16 位值中逐行扫描位

javascript - 上标 .toFixed() 的结果