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

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

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

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

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


当前回答

就像@Shadow2531所说的,你不能直接转换它。如果您的代码将被其他人重用/使用,我还建议您考虑“true”和“false”之外的字符串输入,即“truthy”和“falsy”。这是我使用的:

function parseBoolean(string) {
  switch (String(string).toLowerCase()) {
    case "true":
    case "1":
    case "yes":
    case "y":
      return true;
    case "false":
    case "0":
    case "no":
    case "n":
      return false;
    default:
      //you could throw an error, but 'undefined' seems a more logical reply
      return undefined;
  }
}

其他回答

我在用这个

String.prototype.maybeBool = function(){

    if ( ["yes", "true", "1", "on"].indexOf( this.toLowerCase() ) !== -1 ) return true;
    if ( ["no", "false", "0", "off"].indexOf( this.toLowerCase() ) !== -1 ) return false;

    return this;

}

"on".maybeBool(); //returns true;
"off".maybeBool(); //returns false;
"I like js".maybeBool(); //returns "I like js"

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

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(未定义)));

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

这是我刚刚想到的:

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');
        }
    }
};

我对这个问题的看法是,它旨在满足三个目标:

对于truthy和falsy值,返回true/false,但对于多个字符串值,如果它们是布尔值而不是字符串,则返回truthy或falsy。第二,提供一个弹性接口,使指定值以外的值不会失败,而是返回默认值第三,用尽可能少的代码完成所有这些。

使用JSON的问题是它会导致Javascript错误而失败。该解决方案不具有弹性(尽管它满足1和3):

JSON.parse("FALSE") // fails

此解决方案不够简洁:

if(value === "TRUE" || value === "yes" || ...) { return true; }

我正在为Typecast.js解决这个确切的问题。这三个目标的最佳解决方案是:

return /^true$/i.test(v);

它适用于许多情况,在传入像{}这样的值时不会失败,而且非常简洁。它还返回false作为默认值,而不是undefined或抛出Error,这在松散类型的Javascript开发中更有用。其他的答案都表明了这一点!

这里有很多有趣的答案。真的很惊讶没有人发布此解决方案:

var booleanVal = toCast > '';

这在大多数情况下解析为true,而不是bool false、数字零和空字符串(显然)。您可以在事实之后轻松查找其他假字符串值,例如:

var booleanVal = toCast > '' && toCast != 'false' && toCast != '0';