如何在 JavaScript 中把一个字符串转换为布尔值
JavaScript 有不同的方法将一个字符串转换为布尔值,但这要看情况,或者说,要看你将字符串转换为布尔值的目的,因为我们有两种不同的情况,下面我们将介绍。
第一个场景是将代表布尔值的字符串(例如,true
、false
、yes
、no
、0
、1
)转换为一个固有类型。我们在特定的情况下使用这种方案,例如我们有 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
是一个变量。对于 null
、undefined
、0
、000
、""
和 false
,它返回 false
。对于字符串和空格,它返回 true
。
在上面的例子中,"false"
是一个字符串,因此,Boolean("false")
返回 true
。
对于第一种情况,你可能应该谨慎使用这两种方法,任何不是空字符串的字符串都会通过使用它们来评估为 true
。
相关文章
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 DataFrame 转换为 JSON
发布时间:2024/04/21 浏览次数:153 分类:Python
-
本教程演示了如何将 Pandas DataFrame 转换为 JSON 字符串。
在 Pandas 中加载 JSON 文件
发布时间:2024/04/21 浏览次数:105 分类:Python
-
本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。
Pandas 中的 Join 和 Merge 有什么区别
发布时间:2024/04/20 浏览次数:72 分类:Python
-
本文将为我们介绍 pandas 中 join 和 merge 方法之间的区别。
将 JSON 转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:135 分类:Python
-
本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。