我可以在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));//唯一不起作用的情况

其他回答

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

function asBoolean(value) {

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

}


// asBoolean(true) ==> true
// asBoolean(false) ==> false
// asBoolean('true') ==> true
// asBoolean('false') ==> false
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。其他一切都是假的。当然,您可能希望对输入字符串进行规范化,使其变为小写,并修剪任何空格。

将字符串转换为布尔值

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

将字符串转换为数字

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

可以使用Function从字符串“true”或“false”返回布尔值

const TRUE_OR_FALSE=str=>新函数(“return${str}”)();const[TRUE,FALSE]=[“TRUE”,“FALSE”];常量[T,F]=[TRUE_OR_FALSE(真),TRUE_OR_FALSE(假)];console.log(T,类型T);//`true``“布尔值”`console.log(F,F类型);//`false``“布尔值”`

最简单的方法(假设字符串为“true”或“false”)是:

var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false

对于这些类型的转换,始终使用==运算符而不是==运算符!