我可以在JavaScript中将表示布尔值的字符串(例如“true”、“false”)转换为内部类型吗?

我有一个隐藏的HTML表单,它根据用户在列表中的选择进行更新。此表单包含一些表示布尔值的字段,并用内部布尔值动态填充。但是,一旦将该值放入隐藏的输入字段,它就会变成字符串。

一旦字段转换为字符串,我唯一能找到的确定它的布尔值的方法就是依赖于它的字符串表示的文字值。

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

有没有更好的方法来实现这一点?


当前回答

const boolTrue=JSON.parse(“true”)const boolFalse=JSON.parse(“false”)console.log(boolTrue)//trueconsole.log(boolFalse)//false

要将字符串布尔值(如“true”)转换为实际布尔值,只需包装为JSON.parse()示例:JSON.parse(“true”)

其他回答

如果String对象上有一个函数为我们做这件事,那就太好了,但是我们可以很容易地添加自己的原型来扩展String对象。

在使用之前,将此代码添加到项目中的某个位置。

String.prototype.toBoolean = function() {
   return String(this.valueOf()).toLowerCase() === true.toString();
};

试着这样做:

var myValue = "false"
console.log("Bool is " + myValue.toBoolean())
console.log("Bool is " + "False".toBoolean())
console.log("Bool is " + "FALSE".toBoolean())
console.log("Bool is " + "TRUE".toBoolean())
console.log("Bool is " + "true".toBoolean())
console.log("Bool is " + "True".toBoolean())

因此,最初问题的结果是:

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue.toBoolean();

Do:

var isTrueSet = (myValue === 'true');

使用标识运算符(==),当比较的变量具有不同的类型时,它不会进行任何隐式类型转换。

如果字符串为“true”,则将isTrueSet设置为布尔值true;如果字符串为字符串“false”或根本未设置,则将为布尔值false。


不要:

您可能应该谨慎使用这两种方法来满足您的特定需求:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

任何不是空字符串的字符串都将通过使用它们计算为true。尽管它们是我能想到的关于布尔转换的最干净的方法,但我认为它们并不是你想要的。

记住匹配大小写:

var isTrueSet = (myValue.toLowerCase() === 'true');

此外,如果是表单元素复选框,还可以检测是否选中了该复选框:

var isTrueSet = document.myForm.IS_TRUE.checked;

假设如果选中,则“设置”为true。其计算结果为真/假。

function returnBoolean(str){

    str=str.toString().toLowerCase();

    if(str=='true' || str=='1' || str=='yes' || str=='y' || str=='on' || str=='+'){
        return(true);
    }
    else if(str=='false' || str=='0' || str=='no' || str=='n' || str=='off' || str=='-'){
        return(false);
    }else{
        return(undefined);
    }
}

就像@Shadow2531所说的,你不能直接转换它。如果您的代码将被其他人重用/使用,我还建议您考虑“true”和“false”之外的字符串输入,即“truthy”和“falsy”。这是我使用的:

function parseBoolean(string) {
  switch (String(string).toLowerCase()) {
    case "true":
    case "1":
    case "yes":
    case "y":
      return true;
    case "false":
    case "0":
    case "no":
    case "n":
      return false;
    default:
      //you could throw an error, but 'undefined' seems a more logical reply
      return undefined;
  }
}