迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中把一个字符串转换为布尔值

作者:迹忆客 最近更新:2023/03/10 浏览次数:

JavaScript 有不同的方法将一个字符串转换为布尔值,但这要看情况,或者说,要看你将字符串转换为布尔值的目的,因为我们有两种不同的情况,下面我们将介绍。

第一个场景是将代表布尔值的字符串(例如,truefalseyesno01)转换为一个固有类型。我们在特定的情况下使用这种方案,例如我们有 HTML 表单元素和一个隐藏的表单,它是基于用户在检查输入或选择输入中的选择而显示的。

<input type="checkbox" id="display_hidden_form1" name="display_hidden_form1" value="true">
<label for="display_hidden_form1"> Display hide form1</label><br>

<input type="checkbox" id="display_hidden_form2" name="display_hidden_form2" value="false">
<label for="display_hidden_form2"> Display hide form2</label><br>

<script>
    let myValue = document.getElementById("display_hidden_form1").value;
    let isTrueval = myValue === 'true';

    let myValue2 = document.getElementById("display_hidden_form2").value;
    let isTrueval2 = myValue2 === 'true';

    console.log({isTrueval, isTrueval2});
</script>

输出:

{isTrueval: true, isTrueval2: false}
const convertString = (word) =>{
    switch(word.toLowerCase().trim()){
        case "yes": case "true": case "1": return true;
        case "no": case "false": case "0": case null: return false;
        default: return Boolean(word);
    }
}
console.log(convertString("true"));
console.log(convertString("no"));
console.log(convertString("dasdasd"));

输出:

true
false
true

有两种方法可以将变量转换为布尔值. 首先是通过双 NOT 运算符(!!),其次是通过类型转换 (Boolean(value))

let myBool = Boolean("false"); 

let myBool2 = !!"false";  

console.log({myBool, myBool2});  

输出:

{myBool: true, myBool2: true}

value 是一个变量。对于 nullundefined0000""false,它返回 false。对于字符串和空格,它返回 true

在上面的例子中,"false"是一个字符串,因此,Boolean("false") 返回 true

对于第一种情况,你可能应该谨慎使用这两种方法,任何不是空字符串的字符串都会通过使用它们来评估为 true

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

在 Pandas 中加载 JSON 文件

发布时间:2024/04/21 浏览次数:105 分类:Python

本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。

将 JSON 转换为 Pandas DataFrame

发布时间:2024/04/20 浏览次数:135 分类:Python

本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便