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

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

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

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

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


当前回答

许多现有的答案都是相似的,但大多数人忽略了一个事实,即给定的论点也可能是一个对象。

这是我刚刚想到的:

Utils.parseBoolean = function(val){
    if (typeof val === 'string' || val instanceof String){
        return /true/i.test(val);
    } else if (typeof val === 'boolean' || val instanceof Boolean){
        return new Boolean(val).valueOf();
    } else if (typeof val === 'number' || val instanceof Number){
        return new Number(val).valueOf() !== 0;
    }
    return false;
};

…和它的单元测试

Utils.Tests = function(){
    window.console.log('running unit tests');

    var booleanTests = [
        ['true', true],
        ['false', false],
        ['True', true],
        ['False', false],
        [, false],
        [true, true],
        [false, false],
        ['gibberish', false],
        [0, false],
        [1, true]
    ];

    for (var i = 0; i < booleanTests.length; i++){
        var lhs = Utils.parseBoolean(booleanTests[i][0]);
        var rhs = booleanTests[i][1];
        var result = lhs === rhs;

        if (result){
            console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\t : \tpass');
        } else {
            console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\t : \tfail');
        }
    }
};

其他回答

警告

这个高度支持的传统答案在技术上是正确的,但仅适用于非常特定的场景,当字符串值完全为“true”或“false”时。

传递到下面这些函数的无效json字符串将引发异常。


原答覆:

怎么样

JSON.parse("True".toLowerCase());

或使用jQuery

$.parseJSON("TRUE".toLowerCase());

此函数可以处理字符串以及布尔值真/假。

function stringToBoolean(val){
    var a = {
        'true':true,
        'false':false
    };
    return a[val];
}

演示如下:

函数stringToBoolean(val){变量a={'true':真,“false”:false};返回[val];}console.log(stringToBoolean(“true”));console.log(typeof(stringToBoolean(“true”));console.log(stringToBoolean(“false”));console.log(typeof(stringToBoolean(“false”));console.log(stringToBoolean(true));console.log(typeof(stringToBoolean(true)));console.log(stringToBoolean(false));console.log(typeof(stringToBoolean(false)));console.log(“==========================================”);//如果值未定义呢?console.log(“未定义结果:”+stringToBoolean(未定义));console.log(“未定义结果的类型:”+typeof(stringToBoolean(未定义)));console.log(“==========================================”);//如果值是不相关的字符串呢?console.log(“不相关的字符串结果:”+stringToBoolean(“hello world”));console.log(“不相关字符串结果的类型:”+typeof(stringToBoolean(未定义)));

我编写了一个函数来匹配PHP的filter_var,它做得很好。要点如下:https://gist.github.com/CMCDragonkai/7389368

/**
 * Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation
 * @param  {Mixed}        value 
 * @param  {Boolean}      nullOnFailure = false
 * @return {Boolean|Null}
 */
var parseBooleanStyle = function(value, nullOnFailure = false){
    switch(value){
        case true:
        case 'true':
        case 1:
        case '1':
        case 'on':
        case 'yes':
            value = true;
            break;
        case false:
        case 'false':
        case 0:
        case '0':
        case 'off':
        case 'no':
            value = false;
            break;
        default:
            if(nullOnFailure){
                value = null;
            }else{
                value = false;
            }
            break;
    }
    return value;
};

可以按如下方式使用JSON.parse:

var trueOrFalse=“真”;result=JSON.parse(trueOrFalse.toLowerCase());if(结果==真)警报(“这是真的”);其他的警报(“这是错误的”);

在这种情况下,toLowerCase很重要

我认为它可以用一个带有使用箭头功能的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));//唯一不起作用的情况