首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

JavaScript:解析字符串布尔值?

在JavaScript中,解析字符串布尔值可以使用以下方法:

  1. 使用JSON.parse()函数:
代码语言:javascript
复制
const str = "true";
const boolValue = JSON.parse(str);
console.log(typeof boolValue); // "boolean"
console.log(boolValue); // true
  1. 使用自定义函数:
代码语言:javascript
复制
function parseStringBoolean(str) {
  const boolValue = str.toLowerCase() === "true";
  return boolValue;
}

const str = "True";
const boolValue = parseStringBoolean(str);
console.log(typeof boolValue); // "boolean"
console.log(boolValue); // true

在这个例子中,我们首先将字符串转换为小写,然后检查它是否等于"true"。如果是,则返回true,否则返回false

注意:这种方法只能解析字符串"true"和"false",对于其他字符串可能会产生不正确的结果。在使用这种方法时,请确保输入字符串只包含"true"或"false"。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券