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

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

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

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

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


当前回答

我这样做,将处理1=TRUE=yes=yes=TRUE,0=FALSE=no=no=FALSE:

BOOL=false
if (STRING)
  BOOL=JSON.parse(STRING.toLowerCase().replace('no','false').replace('yes','true'));

用字符串变量的名称替换STRING。

如果不为空,则为数值或以下字符串之一:“true”、“true”、“false”、“false”、“yes”、“yes”、“no”、“no”它会(故意)抛出错误

其他回答

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);
    }
}
function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayır": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}

已经有这么多答案可用了。但在某些情况下,以下内容可能很有用。

// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];

function getBoolean(a) {
    return TRUTHY_VALUES.some(function(t) {
        return t === a;
    });
}

这在具有非布尔值的示例中非常有用。

getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false

getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true

这里有很多有趣的答案。真的很惊讶没有人发布此解决方案:

var booleanVal = toCast > '';

这在大多数情况下解析为true,而不是bool false、数字零和空字符串(显然)。您可以在事实之后轻松查找其他假字符串值,例如:

var booleanVal = toCast > '' && toCast != 'false' && toCast != '0';  

如果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();