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

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

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

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

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


当前回答

/// Convert something to boolean
function toBoolean( o ) {
    if ( null !== o ) {
        let t = typeof o;
        if ( "undefined" !== typeof o ) {
            if ( "string" !== t ) return !!o;
            o = o.toLowerCase().trim();
            return "true" === o || "1" === o;
        }
    }
    return false;
}

toBoolean(false) --> false
toBoolean(true) --> true
toBoolean("false") --> false
toBoolean("true") --> true
toBoolean("TRue") --> true
toBoolean("1") --> true
toBoolean("0") --> false
toBoolean(1) --> true
toBoolean(0) --> false
toBoolean(123.456) --> true
toBoolean(0.0) --> false
toBoolean("") --> false
toBoolean(null) --> false
toBoolean() --> false

其他回答

Do:

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

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

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


不要:

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

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

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

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

对于null、undefined、“”、“false”,“toBoolean”函数返回false。对于任何其他字符串,它都返回true:

const toBoolean = (bool) => {
  if (bool === 'false') bool = false
  return !!bool
}

toBoolean('false') // returns false
if (String(a) == "true"){
  //true block
} else {
  //false block
}
const stringToBoolean = (stringValue) => {
    switch(stringValue?.toLowerCase()?.trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
        case undefined:
          return false;

        default: 
          return JSON.parse(stringValue);
    }
}

如果有其他代码将布尔值转换为字符串,您需要确切地知道该代码如何存储真/假值。要么这样,要么您需要访问反转转换的函数。

有无数种方法可以在字符串中表示布尔值(“true”、“Y”、“1”等)。因此,您不应该依赖一些通用的字符串到布尔值转换器,如布尔值(myValue)。您需要使用一个例程来反转原始布尔值到字符串的转换,无论是什么。

如果您知道它将真布尔值转换为“真”字符串,那么您的示例代码就可以了。除了您应该使用==而不是==,因此没有自动类型转换。