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

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

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

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

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


当前回答

我认为它可以用一个带有使用箭头功能的1行代码完成

const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;

你们可以使用以下代码段运行和测试各种情况

const convertStringToBoolean=(value)=>value?字符串(值).toLowerCase()==“true”:false;console.log(convertStringToBoolean(“a”));console.log(convertStringToBoolean(null));console.log(convertStringToBoolean(未定义));console.log(convertStringToBoolean(“undefined”));console.log(convertStringToBoolean(true));console.log(convertStringToBoolean(false));console.log(convertStringToBoolean(0));console.log(convertStringToBoolean(1));//唯一不起作用的情况

其他回答

我认为它可以用一个带有使用箭头功能的1行代码完成

const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;

你们可以使用以下代码段运行和测试各种情况

const convertStringToBoolean=(value)=>value?字符串(值).toLowerCase()==“true”:false;console.log(convertStringToBoolean(“a”));console.log(convertStringToBoolean(null));console.log(convertStringToBoolean(未定义));console.log(convertStringToBoolean(“undefined”));console.log(convertStringToBoolean(true));console.log(convertStringToBoolean(false));console.log(convertStringToBoolean(0));console.log(convertStringToBoolean(1));//唯一不起作用的情况

我使用以下方法:

function parseBool(b) {
    return !(/^(false|0)$/i).test(b) && !!b;
}

此函数执行通常的布尔强制,字符串“false”(不区分大小写)和“0”除外。

我在用这个

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"

我认为这是非常普遍的:

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

它说:

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

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

function asBoolean(value) {

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

}


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