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

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

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

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

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


当前回答

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

// 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

其他回答

使用这个库要轻松。

https://github.com/rohmanhm/force-boolean

你只需要写一行

const ForceBoolean = require('force-boolean')

const YOUR_VAR = 'false'
console.log(ForceBoolean(YOUR_VAR)) // it's return boolean false

它还支持以下内容

 return false if value is number 0
 return false if value is string '0'
 return false if value is string 'false'
 return false if value is boolean false
 return true if value is number 1
 return true if value is string '1'
 return true if value is string 'true'
 return true if value is boolean 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);
    }
}

Do:

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

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

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


不要:

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

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

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

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

另一种解决方案。jsFiddle公司

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

测试用例在节点中运行

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

简单的解决方案我已经用了一段时间了

function asBoolean(value) {

    return (''+value) === 'true'; 

}


// asBoolean(true) ==> true
// asBoolean(false) ==> false
// asBoolean('true') ==> true
// asBoolean('false') ==> false