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

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

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

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

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


当前回答

/// Convert something to boolean
function toBoolean( o ) {
    if ( null !== o ) {
        let t = typeof o;
        if ( "undefined" !== typeof o ) {
            if ( "string" !== t ) return !!o;
            o = o.toLowerCase().trim();
            return "true" === o || "1" === o;
        }
    }
    return false;
}

toBoolean(false) --> false
toBoolean(true) --> true
toBoolean("false") --> false
toBoolean("true") --> true
toBoolean("TRue") --> true
toBoolean("1") --> true
toBoolean("0") --> false
toBoolean(1) --> true
toBoolean(0) --> false
toBoolean(123.456) --> true
toBoolean(0.0) --> false
toBoolean("") --> false
toBoolean(null) --> false
toBoolean() --> false

其他回答

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

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

这是我提交的一行代码:我需要计算一个字符串和输出,如果为“true”,则为true,如果为false,则为false;如果为“-12.35673”,则是一个数字。

val = 'false';

val = /^false$/i.test(val) ? false : ( /^true$/i.test(val) ? true : val*1 ? val*1 : val );

记住匹配大小写:

var isTrueSet = (myValue.toLowerCase() === 'true');

此外,如果是表单元素复选框,还可以检测是否选中了该复选框:

var isTrueSet = document.myForm.IS_TRUE.checked;

假设如果选中,则“设置”为true。其计算结果为真/假。

var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) { 
    return !falsy.test(val) && !!val;
};

这会为每个假值返回false,为每个真值返回true,但“false”、“f”、“no”、“n”和“0”除外(不区分大小写)。

// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();

//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());

我发现,对布尔值使用“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>

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