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

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

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

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

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


当前回答

此函数可以处理字符串以及布尔值真/假。

function stringToBoolean(val){
    var a = {
        'true':true,
        'false':false
    };
    return a[val];
}

演示如下:

函数stringToBoolean(val){变量a={'true':真,“false”:false};返回[val];}console.log(stringToBoolean(“true”));console.log(typeof(stringToBoolean(“true”));console.log(stringToBoolean(“false”));console.log(typeof(stringToBoolean(“false”));console.log(stringToBoolean(true));console.log(typeof(stringToBoolean(true)));console.log(stringToBoolean(false));console.log(typeof(stringToBoolean(false)));console.log(“==========================================”);//如果值未定义呢?console.log(“未定义结果:”+stringToBoolean(未定义));console.log(“未定义结果的类型:”+typeof(stringToBoolean(未定义)));console.log(“==========================================”);//如果值是不相关的字符串呢?console.log(“不相关的字符串结果:”+stringToBoolean(“hello world”));console.log(“不相关字符串结果的类型:”+typeof(stringToBoolean(未定义)));

其他回答

你为什么不试试这样的

Boolean(JSON.parse((yourString.toString()).toLowerCase()));

当给出其他文本而不是true或false时,无论情况如何,它都会返回一个错误,并且它还会将数字捕获为

// 0-> false
// any other number -> true

注意,也许将来代码会更改并返回布尔值,而不是当前的一个字符串。

解决方案是:

//Currently
var isTrue = 'true';
//In the future (Other developer change the code)
var isTrue = true;
//The solution to both cases
(isTrue).toString() == 'true'

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

function asBoolean(value) {

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

}


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

我认为这是非常普遍的:

if(字符串(a).toLowerCase()==“true”)。。。

它说:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false

可以使用正则表达式:

/*
 * Converts a string to a bool.
 *
 * This conversion will:
 *
 *  - match 'true', 'on', or '1' as true.
 *  - ignore all white-space padding
 *  - ignore capitalization (case).
 *
 * '  tRue  ','ON', and '1   ' will all evaluate as true.
 *
 */
function strToBool(s)
{
    // will match one and only one of the string 'true','1', or 'on' rerardless
    // of capitalization and regardless off surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

如果您喜欢扩展String类,可以执行以下操作:

String.prototype.bool = function() {
    return strToBool(this);
};

alert("true".bool());

对于那些希望扩展String对象以获得此结果但担心可枚举性并担心与扩展String对象的其他代码冲突的人(请参见注释):

Object.defineProperty(String.prototype, "com_example_bool", {
    get : function() {
        return (/^(true|1)$/i).test(this);
    }
});
alert("true".com_example_bool);

(当然在旧版浏览器中不起作用,Firefox显示错误,而Opera、Chrome、Safari和IE显示正确。错误720760)