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

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

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

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

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


当前回答

const stringToBoolean = (stringValue) => {
    switch(stringValue?.toLowerCase()?.trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
        case undefined:
          return false;

        default: 
          return JSON.parse(stringValue);
    }
}

其他回答

从字符串或数字中获取布尔值有一个很好的解决方案:

var boolValue = Boolean(Number('0'));

var boolValue = Boolean(Number('1'));

第一个将返回false,第二个将返回true。

我很惊讶没有人建议我加入

let bool = "false"
bool = !["false", "0", 0].includes(bool)

您可以为true修改检查或包含更多条件(例如null、“”)。

var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1) ? true : false;

甚至只是

var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1);

类似于一些switch语句,但更紧凑。只有当字符串是trueVals字符串之一时,返回的值才会为true。其他一切都是假的。当然,您可能希望对输入字符串进行规范化,使其变为小写,并修剪任何空格。

我需要一个将任何变量类型转换为布尔值的代码。下面是我想到的:

常量toBoolean=(x)=>{if(类型x===“对象”){for(x中的var i)返回truereturn false}返回(x!==null)&&(x!=undefined)&&!['false',“”,“0”,“no”,“off”].includes(x.toString().toLowerCase())}

让我们测试一下!

常量toBoolean=(x)=>{if(类型x===“对象”){for(x中的var i)返回truereturn false}返回(x!==null)&&(x!=undefined)&&!['false',“”,“0”,“no”,“off”].includes(x.toString().toLowerCase())}//让我们测试一下!let falseValues=[false,'false',0,'','off','no',[],{},null,undefined]let trueValues=[true,'true','true',1,-1,'Anything',['填充数组'],{'具有任意键的对象':null}]falseValues.forEach((value,index)=>console.log(`类型为${typeof value}的False值${index}:${value}->${toBoolean(value)}`))trueValues.forEach((value,index)=>console.log(`类型为${typeof value}的True value${index}:${value}->${toBoolean(value)}`))

如果单词“off”和“no”与您的大小写不符,您可以从数组中删除它们。

以下内容就足够了

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

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