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

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

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

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

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


当前回答

上帝啊,这些答案中有些简直太疯狂了。我喜欢JS和它的无数种方式。

我的偏好是:

testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;

其他回答

你为什么不试试这样的

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

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

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

这里有很多有趣的答案。真的很惊讶没有人发布此解决方案:

var booleanVal = toCast > '';

这在大多数情况下解析为true,而不是bool false、数字零和空字符串(显然)。您可以在事实之后轻松查找其他假字符串值,例如:

var booleanVal = toCast > '' && toCast != 'false' && toCast != '0';  

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

常量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”与您的大小写不符,您可以从数组中删除它们。

将字符串转换为布尔值

var vIn = "true";
var vOut = vIn.toLowerCase()=="true"?1:0;

将字符串转换为数字

var vIn = 0;
var vOut = parseInt(vIn,10/*base*/);

//尝试两种方法将字符串转换为布尔值

    const checkBoolean = Boolean("false"); 
    const checkBoolean1 = !!"false";  
    
    console.log({checkBoolean, checkBoolean1});