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

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

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

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

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


当前回答

const boolTrue=JSON.parse(“true”)const boolFalse=JSON.parse(“false”)console.log(boolTrue)//trueconsole.log(boolFalse)//false

要将字符串布尔值(如“true”)转换为实际布尔值,只需包装为JSON.parse()示例:JSON.parse(“true”)

其他回答

function isTrue(val) {
    try {
        return !!JSON.parse(val);
    } catch {
        return false;
    }
}
/// 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

我编写了一个助手函数来处理您的案例(以及其他一些)。根据您的具体需要随意更改

/**
 * @example
 * <code>
 * var pageRequestParams = {'enableFeatureX': 'true'};
 * toBool(pageRequestParams.enableFeatureX);  // returns true
 *
 * toBool(pageRequestParams.enableFeatureY, true, options.enableFeatureY)
 * </code>
 * @param {*}value
 * @param {Boolean}[mapEmptyStringToTrue=false]
 * @param {Boolean}[defaultVal=false] this is returned if value is undefined.
 *
 * @returns {Boolean}
 * @example
 * <code>
 * toBool({'enableFeatureX': ''        }.enableFeatureX);          // false
 * toBool({'enableFeatureX': ''        }.enableFeatureX, true);    // true
 * toBool({                            }.enableFeatureX, true);    // false
 * toBool({'enableFeatureX': 0         }.enableFeatureX);          // false
 * toBool({'enableFeatureX': '0'       }.enableFeatureX);          // false
 * toBool({'enableFeatureX': '0 '      }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'false'   }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'falsE '  }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'no'      }.enableFeatureX);          // false
 *
 * toBool({'enableFeatureX': 1         }.enableFeatureX);          // true
 * toBool({'enableFeatureX': '-2'      }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'true'    }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'false_'  }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'john doe'}.enableFeatureX);          // true
 * </code>
 *
 */
var toBool = function (value, mapEmptyStringToTrue, defaultVal) {
    if (value === undefined) {return Boolean(defaultVal); }
    mapEmptyStringToTrue = mapEmptyStringToTrue !== undefined ? mapEmptyStringToTrue : false; // default to false
    var strFalseValues = ['0', 'false', 'no'].concat(!mapEmptyStringToTrue ? [''] : []);
    if (typeof value === 'string') {
        return (strFalseValues.indexOf(value.toLowerCase().trim()) === -1);
    }
    // value is likely null, boolean, or number
    return Boolean(value);
};

警告

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

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


原答覆:

怎么样

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

或使用jQuery

$.parseJSON("TRUE".toLowerCase());
    MyLib.Convert.bool = function(param) {
         var res = String(param).toLowerCase();
         return !(!Boolean(res) || res === "false" || res === "0");
     };