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

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

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

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

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


当前回答

将字符串转换为布尔值的最简单方法如下:

Boolean(<stringVariable>)

其他回答

这里有一个简单的函数,

   function convertStringToBool(str){
        return ((str === "True") || (str === "true")) ? true:false;
    }

这将产生以下结果

convertStringToBool("false") //returns false
convertStringToBool("true") // returns true
convertStringToBool("False") // returns false
convertStringToBool("True") // returns true

@guinaps>任何不是空字符串的字符串都将通过使用它们计算为true。

如何使用String.match()方法

var str="true";
var boolStr=Boolean(str.match(/^true$/i)); 

这本身不会得到1/0或yes/no,但它会捕捉到TRUE/TRUE,同时,它也会为任何碰巧有“TRUE”作为子字符串的字符串返回false。

EDIT

下面是一个处理真/假、1/0、是/否(不区分大小写)的函数

​function stringToBool(str) {
    var bool;
    if (str.match(/^(true|1|yes)$/i) !== null) {
        bool = true;
    } else if (str.match(/^(false|0|no)*$/i) !== null) {
        bool = false;
    } else {
        bool = null;
        if (console) console.log('"' + str + '" is not a boolean value');
    }
    return bool;
}

stringToBool('1'); // true
stringToBool('No'); // false
stringToBool('falsey'); // null ("falsey" is not a boolean value.)
stringToBool(''); // false

工作完美且非常简单:

var boolean = "false";
boolean = (boolean === "true");

//boolean = JSON.parse(boolean); //or this way.. 

要测试它:

var boolean=“false”;boolean=(boolean==“true”);//boolean=JSON.parse(布尔值)//或者这样。。if(布尔值==真){alert(“boolean=”+boolean);}其他{alert(“boolean=”+boolean);}

另一种解决方案。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
> 

如果需要字符串值中的布尔值false和true,则执行简单的单行操作:

storeBooleanHere = stringVariable=="true"?true:false;

storeBooleanHere-此变量将保存布尔值stringVariable-将布尔值存储为字符串的变量