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

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

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

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

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


当前回答

我在用这个

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"

其他回答

我编写了一个函数来匹配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;
};
String(true).toLowerCase() == 'true'; // true
String("true").toLowerCase() == 'true'; // true
String("True").toLowerCase() == 'true'; // true
String("TRUE").toLowerCase() == 'true'; // true

String(false).toLowerCase() == 'true'; // false

如果您不确定输入,上述方法适用于布尔值和任何字符串。

我使用这个简单的方法(使用“myVarToTest”):

var trueValuesRange = ['1', 1, 'true', true];

myVarToTest = (trueValuesRange.indexOf(myVarToTest) >= 0);

在HTML中,属性的值最终变成字符串。为了在不希望出现的情况下减轻这种情况,您可以使用一个函数将它们有条件地解析为它们在JavaScript或任何其他感兴趣的编程语言中表示的值。

以下是从字符串类型恢复布尔类型的说明,但它也可以进一步扩展到其他数据类型,如数字、数组或对象。

除此之外,JSON.parse还有一个作为函数的复活参数。它也可以用来实现同样的目的。

让我们调用一个看起来像布尔值的字符串“true”,一个布尔值字符串,同样我们也可以调用一个像数字“1”的字符串,一个数字字符串。然后我们可以确定字符串是否为布尔字符串:

const isBooleanString = (string) => ['true', 'false'].some(item => item === string);

之后,我们需要通过JSON.parse方法将布尔字符串解析为JSON:

JSON.parse(aBooleanString);

但是,任何不是布尔字符串、数字字符串或任何字符串化对象或数组(任何无效的JSON)的字符串都会导致JSON.parse方法抛出SyntaxError。

因此,您需要知道如何调用它,即它是否为布尔字符串。您可以通过编写一个函数来实现这一点,该函数进行上述定义的布尔字符串检查并调用JSON.parse:

function parse(string){
  return isBooleanString(string) ? JSON.parse(string)
    : string;
}

通过进一步参数化isBooleanString实用程序以接受接受的布尔字符串的可选数组,可以进一步概括isBooleanString实用程序,从而对什么是布尔字符串具有更广泛的视角:

const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) => spec.some(item => item === string);

我需要一个将任何变量类型转换为布尔值的代码。下面是我想到的:

常量toBoolean=(x)=>{if(类型x===“对象”){for(x中的var i)返回truereturn false}返回(x!==null)&&(x!=undefined)&&!['false',“”,“0”,“no”,“off”].includes(x.toString().toLowerCase())}

让我们测试一下!

常量toBoolean=(x)=>{if(类型x===“对象”){for(x中的var i)返回truereturn false}返回(x!==null)&&(x!=undefined)&&!['false',“”,“0”,“no”,“off”].includes(x.toString().toLowerCase())}//让我们测试一下!let falseValues=[false,'false',0,'','off','no',[],{},null,undefined]let trueValues=[true,'true','true',1,-1,'Anything',['填充数组'],{'具有任意键的对象':null}]falseValues.forEach((value,index)=>console.log(`类型为${typeof value}的False值${index}:${value}->${toBoolean(value)}`))trueValues.forEach((value,index)=>console.log(`类型为${typeof value}的True value${index}:${value}->${toBoolean(value)}`))

如果单词“off”和“no”与您的大小写不符,您可以从数组中删除它们。