我可以在JavaScript中将表示布尔值的字符串(例如“true”、“false”)转换为内部类型吗?
我有一个隐藏的HTML表单,它根据用户在列表中的选择进行更新。此表单包含一些表示布尔值的字段,并用内部布尔值动态填充。但是,一旦将该值放入隐藏的输入字段,它就会变成字符串。
一旦字段转换为字符串,我唯一能找到的确定它的布尔值的方法就是依赖于它的字符串表示的文字值。
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == '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”与您的大小写不符,您可以从数组中删除它们。
已经有这么多答案可用了。但在某些情况下,以下内容可能很有用。
// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];
function getBoolean(a) {
return TRUTHY_VALUES.some(function(t) {
return t === a;
});
}
这在具有非布尔值的示例中非常有用。
getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false
getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true