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

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

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

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

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


当前回答

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

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

其他回答

我使用自己的方法,其中包括检查对象是否首先存在,以及更直观地转换为布尔值:

function str2bool(strvalue){
  return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);
}

结果如下:

var test; // false
var test2 = null; // false
var test3 = 'undefined'; // false
var test4 = 'true'; // true
var test5 = 'false'; // false
var test6 = true; // true
var test7 = false; // false
var test8 = 1; // true
var test9 = 0; // false
var test10 = '1'; // true
var test11 = '0'; // false

小提琴:http://jsfiddle.net/av5xcj6s/

以下内容就足够了

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

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

我发现,对布尔值使用“1”和空值“”比使用“true”或“false”字符串值更有效。。。特别是对于html表单,因为Dom元素中的未初始化/空值将始终求值为false,而其中的任何值都求值为true。

例如:

<input type='button' onclick='this.value = tog(this.value);' />

<script type="text/javascript">

    function tog(off) {
        if(off) {
            alert('true, toggle to false');
            return '';
        } else {
            alert('false, toggle to true');
            return '1';
        }
    }   
</script>

似乎是一条更容易的路,到目前为止,这条路一直很稳定/容易。。。也许有人能找到打破这种局面的方法?

你为什么不试试这样的

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

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

// 0-> false
// any other number -> true
function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayır": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}