我可以在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(未定义)));

其他回答

我在用这个

String.prototype.maybeBool = function(){

    if ( ["yes", "true", "1", "on"].indexOf( this.toLowerCase() ) !== -1 ) return true;
    if ( ["no", "false", "0", "off"].indexOf( this.toLowerCase() ) !== -1 ) return false;

    return this;

}

"on".maybeBool(); //returns true;
"off".maybeBool(); //returns false;
"I like js".maybeBool(); //returns "I like js"

你甚至不需要使用变量,如果你知道'true'总是小写,你可以使用返回true或false的变量:

(eval(yourBooleanString == 'true'))

以下内容就足够了

String.prototype.boolean = function() {
    return "true" == this; 
};

"true".boolean() // returns true "false".boolean() // returns false

Do:

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

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

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


不要:

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

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

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

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

你要找的表达方式很简单

/^true$/i.test(myValue)

如中所示

var isTrueSet = /^true$/i.test(myValue);

这将根据正则表达式测试myValue,不区分大小写,并且不会修改原型。

示例:

/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz");  // returns false