如何在JavaScript中转换字符串到布尔值?

时间:2022-03-09 16:56:41

Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

我能否将表示布尔值的字符串(例如,“true”,“false”)转换为JavaScript内的固有类型?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

我在HTML中有一个隐藏的表单,它是根据用户在列表中的选择更新的。该表单包含一些表示布尔值的字段,并使用一个内部布尔值动态填充。然而,一旦这个值被放置到隐藏的输入字段中,它就变成了一个字符串。

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

我能找到确定字段的布尔值的唯一方法,一旦它被转换成一个字符串,就取决于它的字符串表示的文字值。

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

Is there a better way to accomplish this?

有没有更好的方法来实现这个目标?

71 个解决方案

#1


2296  

Do:

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

Unnecessary:

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==), which does:

通过使用identity运算符(==),可以使它变得更严格,当比较的变量有不同类型时,它不会产生任何隐式类型转换,而不使用相等运算符(==):

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

Don't:

You should probably be cautious about using these two methods for your specific needs:

您应该谨慎使用这两种方法来满足您的特定需求:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

任何不是空字符串的字符串都将通过使用它们来进行评估。虽然它们是我能想到的关于布尔转换的最干净的方法,但我认为它们不是你要找的。

#2


497  

Warning

This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false" (MUST be lowercase as well).

这个高度向上的遗留答案在技术上是正确的,但是只涵盖了非常具体的场景,当您的字符串值完全是“true”或“false”时(必须是小写的)。

An invalid json string passed into these functions below WILL throw an exception.

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


Original answer:

最初的回答:

How about?

怎么样?

JSON.parse("true");

or with jQuery

与jQuery或

$.parseJSON("true");

#3


180  

stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}

#4


112  

I think this is much universal:

我认为这是非常普遍的:

if (String(a) == "true") ...

if (String(a) == "true")…

It goes:

它是:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false

#5


104  

You can use regular expressions:

你可以使用正则表达式:

/*
 * Converts a string to a bool.
 *
 * This conversion will:
 *
 *  - match 'true', 'on', or '1' as true.
 *  - ignore all white-space padding
 *  - ignore capitalization (case).
 *
 * '  tRue  ','ON', and '1   ' will all evaluate as true.
 *
 */
function strToBool(s)
{
    // will match one and only one of the string 'true','1', or 'on' rerardless
    // of capitalization and regardless off surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

If you like extending the String class you can do:

如果您喜欢扩展String类,您可以这样做:

String.prototype.bool = function() {
    return strToBool(this);
};

alert("true".bool());

For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about *ing with other code that extends the String object:

对于那些想要扩展字符串对象来得到这个的(请参阅注释),但是他们担心枚举能力,并且担心与扩展字符串对象的其他代码发生冲突:

Object.defineProperty(String.prototype, "com_example_bool", {
    get : function() {
        return (/^(true|1)$/i).test(this);
    }
});
alert("true".com_example_bool);

(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)

(当然,在老版本的浏览器中无法工作,而Firefox则显示错误,而Opera、Chrome、Safari和IE则显示为真。错误720760)

#6


102  

Remember to match case:

记得比赛的例子:

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

Also, if it's a form element checkbox, you can also detect if the checkbox is checked:

另外,如果它是一个表单元素复选框,也可以检测复选框是否被选中:

var isTrueSet = document.myForm.IS_TRUE.checked;

Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.

假设它被检查,它是“set”等于true。这个值为true / false。

#7


38  

Wood-eye be careful. After seeing the consequences after applying the the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:

Wood-eye小心些而已。在看完500+以上的最高答案后,我觉得有义务发布一些实际有用的东西:

Let's start with the shortest, but very strict way:

让我们从最简短,但非常严格的方式开始:

var str = "true";
var mybool = JSON.parse(str);

And end with a proper, more tolerant way:

以一种适当的,更宽容的方式结束:

var parseBool = function(str) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)

    if(str == null)
        return false;

    if (typeof str === 'boolean')
    {
        return (str === true);
    } 

    if(typeof str === 'string')
    {
        if(str == "")
            return false;

        str = str.replace(/^\s+|\s+$/g, '');
        if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
            return true;

        str = str.replace(/,/g, '.');
        str = str.replace(/^\s*\-\s*/g, '-');
    }

    // var isNum = string.match(/^[0-9]+$/) != null;
    // var isNum = /^\d+$/.test(str);
    if(!isNaN(str))
        return (parseFloat(str) != 0);

    return false;
}

Testing:

测试:

var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", "  true  ", "  TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");

var array_2 = new Array(null, "", false, "false", "   false   ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");


for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}

for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}

for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}

#8


27  

Your solution is fine.

你的解决方案很好。

Using === would just be silly in this case, as the field's value will always be a String.

在这种情况下,使用===是愚蠢的,因为字段的值始终是一个字符串。

#9


23  

Universal solution with JSON parse:

使用JSON解析的通用解决方案:

function getBool(val) {
    return !!JSON.parse(String(val).toLowerCase());
}

getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false

UPDATE (without JSON):

更新(没有JSON):

function getBool(val){ 
    var num = +val;
    return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}

I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/

我还创建了fiddle来测试它http://jsfiddle.net/da/2grhg/。

#10


22  

I thought that @Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:

我认为@Steven的答案是最好的,并且处理了更多的情况,而不是传入的值只是一个字符串。我想扩展一下,并提供如下内容:

function isTrue(value){
    if (typeof(value) === 'string'){
        value = value.trim().toLowerCase();
    }
    switch(value){
        case true:
        case "true":
        case 1:
        case "1":
        case "on":
        case "yes":
            return true;
        default: 
            return false;
    }
}

It's not necessary to cover all the false cases if you already know all of the true cases you'd have to account for. You can pass anything into this method that could pass for a true value (or add others, it's pretty straightforward), and everything else would be considered false

如果你已经知道了所有的真实情况,那么就没有必要去掩盖所有的错误。您可以将任何东西传递到这个方法中,这个方法可以传递一个真正的值(或者添加其他的值,非常简单),其他的都被认为是假的。

#11


19  

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

This returns false for every falsy value and true for every truthy value except for 'false', 'f', 'no', 'n', and '0' (case-insensitive).

这将为每个假值返回false,除了“false”、“f”、“no”、“n”和“0”(不区分大小写)之外的每一个truthy值都是正确的。

// 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());

#12


17  

The Boolean object doesn't have a 'parse' method. Boolean('false') returns true, so that won't work. !!'false' also returns true, so that won't work also.

布尔对象没有“解析”方法。布尔('false')返回true,因此不会起作用。! !“false”也返回true,因此也不能工作。

If you want string 'true' to return boolean true and string 'false' to return boolean false, then the simplest solution is to use eval(). eval('true') returns true and eval('false') returns false. Keep in mind the performance implications when using eval() though.

如果您希望string 'true'返回布尔true和string 'false'返回布尔false,那么最简单的解决方案是使用eval()。eval('true')返回true, eval('false')返回false。请记住使用eval()时的性能影响。

#13


15  

I use the following:

我使用下面的:

function parseBool(b) {
    return !(/^(false|0)$/i).test(b) && !!b;
}

This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".

这个函数执行通常的布尔强制,除了字符串“false”(不区分大小写)和“0”。

#14


14  

Boolean.parse = function (str) {
  switch (str.toLowerCase ()) {
    case "true":
      return true;
    case "false":
      return false;
    default:
      throw new Error ("Boolean.parse: Cannot convert string to boolean.");
  }
};

#15


11  

The expression you're looking for simply is

你所寻找的表达方式就是。

/^true$/i.test(myValue)

as in

就像在

var isTrueSet = /^true$/i.test(myValue);

This tests myValue against a regular expression , case-insensitive, and doesn't modify the prototype.

这个测试myValue对一个正则表达式,不区分大小写,并且不修改原型。

Examples:

例子:

/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz");  // returns false

#16


11  

There are already so many answers available. But following can be useful in some scenarios.

已经有太多的答案了。但在某些情况下,以下方法是有用的。

// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];

function getBoolean(a) {
    return TRUTHY_VALUES.some(function(t) {
        return t === a;
    });
}

This can be useful where one examples with non-boolean values.

这在具有非布尔值的示例中非常有用。

getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false

getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true

#17


10  

There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.

有很多答案,很难选一个。在我的例子中,我在选择时优先考虑性能,所以我创建了这个jsPerf,希望能在这里提供一些启发。

Brief of results (the higher the better):

结果简介(越高越好):

  1. Conditional statement: 2,826,922
  2. 条件语句:2826922
  3. Switch case on Bool object: 2,825,469
  4. Bool对象上的Switch case: 2,825,469。
  5. Casting to JSON: 1,867,774
  6. 铸造JSON:1867774
  7. !! conversions: 805,322
  8. ! !转换:805322
  9. Prototype of String: 713,637
  10. 字符串的原型:713637

They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.

它们与相关的答案联系在一起,在那里你可以找到关于每一个的更多信息(赞成和反对);特别在评论中。

#18


8  

Hands down the easiest way (assuming you string will be 'true' or 'false') is:

用最简单的方法(假设你的弦是“真”或“假”)是:

var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false

Always use the === operator instead of the == operator for these types of conversions!

对于这些类型的转换,始终使用===操作符而不是==操作符!

#19


8  

Like @Shadow2531 said, you can't just convert it directly. I'd also suggest that you consider string inputs besides "true" and "false" that are 'truthy' and 'falsey' if your code is going to be reused/used by others. This is what I use:

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

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

#20


8  

To convert both string("true", "false") and boolean to boolean

要将两个字符串(“true”、“false”)和布尔值转换为布尔值。

('' + flag) === "true"

Where flag can be

在国旗可以

 var flag = true
 var flag = "true"
 var flag = false
 var flag = "false"

#21


8  

I'm using this one

我用这个

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"

#22


8  

This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive

这已经从被接受的答案中得到了,但它确实有一个很弱的点,我很震惊它是怎么得到这样的结果的,问题是你必须考虑字符串的情况因为这是区分大小写的。

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

#23


7  

My take on this question is that it aims to satisfy three objectives:

我对这个问题的看法是,它的目标是实现三个目标:

  • Return true/false for truthy and falsey values, but also return true/false for multiple string values that would be truthy or falsey if they were Booleans instead of strings.
  • 返回true/false,用于truthy和falsey值,但如果它们是布尔值而不是字符串,则返回true/false。
  • Second, provide a resilient interface so that values other than those specified will not fail, but rather return a default value
  • 其次,提供一个有弹性的接口,这样除指定的值以外的值不会失败,而是返回一个默认值。
  • Third, do all this with as little code as possible.
  • 第三,尽量少用代码。

The problem with using JSON is that it fails by causing a Javascript error. This solution is not resilient (though it satisfies 1 and 3):

使用JSON的问题在于它不会导致Javascript错误。这个解决方案没有弹性(尽管它满足1和3):

JSON.parse("FALSE") // fails

This solution is not concise enough:

这个解决方案不够简洁:

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

I am working on solving this exact problem for Typecast.js. And the best solution to all three objectives is this one:

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

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

It works for many cases, does not fail when values like {} are passed in, and is very concise. Also it returns false as the default value rather than undefined or throwing an Error, which is more useful in loosely-typed Javascript development. Bravo to the other answers that suggested it!

它适用于许多情况,在传入的值(比如{})时不会失败,而且非常简洁。同样,它返回false作为默认值,而不是未定义或抛出错误,这在松散类型的Javascript开发中更有用。对其他的答案来说,太棒了!

#24


7  

another solution. jsFiddle

另一个解决方案。jsFiddle

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

test cases run in node

测试用例在节点中运行。

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

#25


6  

You need to separate (in your thinking) the value of your selections and the representation of that value.

您需要将选择的值和该值的表示分开(在您的思想中)。

Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)

在JavaScript逻辑中选择一个点,它们需要从字符串哨兵转换为本地类型,并在那里进行比较,最好是在需要转换的每个值上只执行一次。记住,如果字符串sentinel不是脚本所知道的(即默认为true或false),则需要处理什么情况。

In other words, yes, you need to depend on the string's value. :-)

换句话说,是的,您需要依赖于字符串的值。:-)

#26


6  

I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/filthy-ness but includes "false" as an acceptible value for false.

我有点晚了,但是我有一个小片段来做这个,它实际上维护了所有的jscript truthey/falsey/filthy-ness,但是包括“false”作为一个可接受的false值。

I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.

我更喜欢这种方法,因为它不依赖于第三方来解析代码(我。e: eval/JSON.parse),这在我的头脑中是多余的,它足够短,不需要一个实用程序函数,并且维护其他的truthey/falsey约定。

var value = "false";
var result = (value == "false") != Boolean(value);

// value = "true"  => result = true
// value = "false" => result = false
// value = true    => result = true
// value = false   => result = false
// value = null    => result = false
// value = []      => result = true
// etc..

#27


5  

function parseBool(value) {
    if (typeof value === "boolean") return value;

    if (typeof value === "number") {
        return value === 1 ? true : value === 0 ? false : undefined;
    }

    if (typeof value != "string") return undefined;

    return value.toLowerCase() === 'true' ? true : false;
}

#28


5  

I wrote a function to match PHP's filter_var which does this nicely. Available in a gist: https://gist.github.com/CMCDragonkai/7389368

我编写了一个函数来匹配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;
};

#29


5  

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

If you are not sure of the input, the above works for boolean and as well any string.

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

#30


4  

I've found that using '1' and an empty value '' for boolean values works far more predictably than 'true' or 'false' string values... specifically with html forms since uninitialized/empty values in Dom elements will consistently evaluate to false whereas any value within them evaluates to true.

我发现,使用'1'和一个空值'用于布尔值,比'true'或'false' string值更容易预测……特别是html表单,因为Dom元素中的未初始化/空值将始终对错误进行评估,而其中的任何值都将计算为true。

For instance:

例如:

<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>

Just seemed like an easier road, so far it's been very consistent/easy... perhaps someone can determine a way to break this?

就像一条更容易的路,到目前为止,它是非常一致/容易的……也许有人能决定一种方法来打破这种局面?

#1


2296  

Do:

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

Unnecessary:

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==), which does:

通过使用identity运算符(==),可以使它变得更严格,当比较的变量有不同类型时,它不会产生任何隐式类型转换,而不使用相等运算符(==):

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

Don't:

You should probably be cautious about using these two methods for your specific needs:

您应该谨慎使用这两种方法来满足您的特定需求:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

任何不是空字符串的字符串都将通过使用它们来进行评估。虽然它们是我能想到的关于布尔转换的最干净的方法,但我认为它们不是你要找的。

#2


497  

Warning

This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false" (MUST be lowercase as well).

这个高度向上的遗留答案在技术上是正确的,但是只涵盖了非常具体的场景,当您的字符串值完全是“true”或“false”时(必须是小写的)。

An invalid json string passed into these functions below WILL throw an exception.

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


Original answer:

最初的回答:

How about?

怎么样?

JSON.parse("true");

or with jQuery

与jQuery或

$.parseJSON("true");

#3


180  

stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}

#4


112  

I think this is much universal:

我认为这是非常普遍的:

if (String(a) == "true") ...

if (String(a) == "true")…

It goes:

它是:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false

#5


104  

You can use regular expressions:

你可以使用正则表达式:

/*
 * Converts a string to a bool.
 *
 * This conversion will:
 *
 *  - match 'true', 'on', or '1' as true.
 *  - ignore all white-space padding
 *  - ignore capitalization (case).
 *
 * '  tRue  ','ON', and '1   ' will all evaluate as true.
 *
 */
function strToBool(s)
{
    // will match one and only one of the string 'true','1', or 'on' rerardless
    // of capitalization and regardless off surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

If you like extending the String class you can do:

如果您喜欢扩展String类,您可以这样做:

String.prototype.bool = function() {
    return strToBool(this);
};

alert("true".bool());

For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about *ing with other code that extends the String object:

对于那些想要扩展字符串对象来得到这个的(请参阅注释),但是他们担心枚举能力,并且担心与扩展字符串对象的其他代码发生冲突:

Object.defineProperty(String.prototype, "com_example_bool", {
    get : function() {
        return (/^(true|1)$/i).test(this);
    }
});
alert("true".com_example_bool);

(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)

(当然,在老版本的浏览器中无法工作,而Firefox则显示错误,而Opera、Chrome、Safari和IE则显示为真。错误720760)

#6


102  

Remember to match case:

记得比赛的例子:

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

Also, if it's a form element checkbox, you can also detect if the checkbox is checked:

另外,如果它是一个表单元素复选框,也可以检测复选框是否被选中:

var isTrueSet = document.myForm.IS_TRUE.checked;

Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.

假设它被检查,它是“set”等于true。这个值为true / false。

#7


38  

Wood-eye be careful. After seeing the consequences after applying the the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:

Wood-eye小心些而已。在看完500+以上的最高答案后,我觉得有义务发布一些实际有用的东西:

Let's start with the shortest, but very strict way:

让我们从最简短,但非常严格的方式开始:

var str = "true";
var mybool = JSON.parse(str);

And end with a proper, more tolerant way:

以一种适当的,更宽容的方式结束:

var parseBool = function(str) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)

    if(str == null)
        return false;

    if (typeof str === 'boolean')
    {
        return (str === true);
    } 

    if(typeof str === 'string')
    {
        if(str == "")
            return false;

        str = str.replace(/^\s+|\s+$/g, '');
        if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
            return true;

        str = str.replace(/,/g, '.');
        str = str.replace(/^\s*\-\s*/g, '-');
    }

    // var isNum = string.match(/^[0-9]+$/) != null;
    // var isNum = /^\d+$/.test(str);
    if(!isNaN(str))
        return (parseFloat(str) != 0);

    return false;
}

Testing:

测试:

var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", "  true  ", "  TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");

var array_2 = new Array(null, "", false, "false", "   false   ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");


for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}

for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}

for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}

#8


27  

Your solution is fine.

你的解决方案很好。

Using === would just be silly in this case, as the field's value will always be a String.

在这种情况下,使用===是愚蠢的,因为字段的值始终是一个字符串。

#9


23  

Universal solution with JSON parse:

使用JSON解析的通用解决方案:

function getBool(val) {
    return !!JSON.parse(String(val).toLowerCase());
}

getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false

UPDATE (without JSON):

更新(没有JSON):

function getBool(val){ 
    var num = +val;
    return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}

I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/

我还创建了fiddle来测试它http://jsfiddle.net/da/2grhg/。

#10


22  

I thought that @Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:

我认为@Steven的答案是最好的,并且处理了更多的情况,而不是传入的值只是一个字符串。我想扩展一下,并提供如下内容:

function isTrue(value){
    if (typeof(value) === 'string'){
        value = value.trim().toLowerCase();
    }
    switch(value){
        case true:
        case "true":
        case 1:
        case "1":
        case "on":
        case "yes":
            return true;
        default: 
            return false;
    }
}

It's not necessary to cover all the false cases if you already know all of the true cases you'd have to account for. You can pass anything into this method that could pass for a true value (or add others, it's pretty straightforward), and everything else would be considered false

如果你已经知道了所有的真实情况,那么就没有必要去掩盖所有的错误。您可以将任何东西传递到这个方法中,这个方法可以传递一个真正的值(或者添加其他的值,非常简单),其他的都被认为是假的。

#11


19  

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

This returns false for every falsy value and true for every truthy value except for 'false', 'f', 'no', 'n', and '0' (case-insensitive).

这将为每个假值返回false,除了“false”、“f”、“no”、“n”和“0”(不区分大小写)之外的每一个truthy值都是正确的。

// 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());

#12


17  

The Boolean object doesn't have a 'parse' method. Boolean('false') returns true, so that won't work. !!'false' also returns true, so that won't work also.

布尔对象没有“解析”方法。布尔('false')返回true,因此不会起作用。! !“false”也返回true,因此也不能工作。

If you want string 'true' to return boolean true and string 'false' to return boolean false, then the simplest solution is to use eval(). eval('true') returns true and eval('false') returns false. Keep in mind the performance implications when using eval() though.

如果您希望string 'true'返回布尔true和string 'false'返回布尔false,那么最简单的解决方案是使用eval()。eval('true')返回true, eval('false')返回false。请记住使用eval()时的性能影响。

#13


15  

I use the following:

我使用下面的:

function parseBool(b) {
    return !(/^(false|0)$/i).test(b) && !!b;
}

This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".

这个函数执行通常的布尔强制,除了字符串“false”(不区分大小写)和“0”。

#14


14  

Boolean.parse = function (str) {
  switch (str.toLowerCase ()) {
    case "true":
      return true;
    case "false":
      return false;
    default:
      throw new Error ("Boolean.parse: Cannot convert string to boolean.");
  }
};

#15


11  

The expression you're looking for simply is

你所寻找的表达方式就是。

/^true$/i.test(myValue)

as in

就像在

var isTrueSet = /^true$/i.test(myValue);

This tests myValue against a regular expression , case-insensitive, and doesn't modify the prototype.

这个测试myValue对一个正则表达式,不区分大小写,并且不修改原型。

Examples:

例子:

/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz");  // returns false

#16


11  

There are already so many answers available. But following can be useful in some scenarios.

已经有太多的答案了。但在某些情况下,以下方法是有用的。

// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];

function getBoolean(a) {
    return TRUTHY_VALUES.some(function(t) {
        return t === a;
    });
}

This can be useful where one examples with non-boolean values.

这在具有非布尔值的示例中非常有用。

getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false

getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true

#17


10  

There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.

有很多答案,很难选一个。在我的例子中,我在选择时优先考虑性能,所以我创建了这个jsPerf,希望能在这里提供一些启发。

Brief of results (the higher the better):

结果简介(越高越好):

  1. Conditional statement: 2,826,922
  2. 条件语句:2826922
  3. Switch case on Bool object: 2,825,469
  4. Bool对象上的Switch case: 2,825,469。
  5. Casting to JSON: 1,867,774
  6. 铸造JSON:1867774
  7. !! conversions: 805,322
  8. ! !转换:805322
  9. Prototype of String: 713,637
  10. 字符串的原型:713637

They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.

它们与相关的答案联系在一起,在那里你可以找到关于每一个的更多信息(赞成和反对);特别在评论中。

#18


8  

Hands down the easiest way (assuming you string will be 'true' or 'false') is:

用最简单的方法(假设你的弦是“真”或“假”)是:

var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false

Always use the === operator instead of the == operator for these types of conversions!

对于这些类型的转换,始终使用===操作符而不是==操作符!

#19


8  

Like @Shadow2531 said, you can't just convert it directly. I'd also suggest that you consider string inputs besides "true" and "false" that are 'truthy' and 'falsey' if your code is going to be reused/used by others. This is what I use:

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

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

#20


8  

To convert both string("true", "false") and boolean to boolean

要将两个字符串(“true”、“false”)和布尔值转换为布尔值。

('' + flag) === "true"

Where flag can be

在国旗可以

 var flag = true
 var flag = "true"
 var flag = false
 var flag = "false"

#21


8  

I'm using this one

我用这个

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"

#22


8  

This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive

这已经从被接受的答案中得到了,但它确实有一个很弱的点,我很震惊它是怎么得到这样的结果的,问题是你必须考虑字符串的情况因为这是区分大小写的。

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

#23


7  

My take on this question is that it aims to satisfy three objectives:

我对这个问题的看法是,它的目标是实现三个目标:

  • Return true/false for truthy and falsey values, but also return true/false for multiple string values that would be truthy or falsey if they were Booleans instead of strings.
  • 返回true/false,用于truthy和falsey值,但如果它们是布尔值而不是字符串,则返回true/false。
  • Second, provide a resilient interface so that values other than those specified will not fail, but rather return a default value
  • 其次,提供一个有弹性的接口,这样除指定的值以外的值不会失败,而是返回一个默认值。
  • Third, do all this with as little code as possible.
  • 第三,尽量少用代码。

The problem with using JSON is that it fails by causing a Javascript error. This solution is not resilient (though it satisfies 1 and 3):

使用JSON的问题在于它不会导致Javascript错误。这个解决方案没有弹性(尽管它满足1和3):

JSON.parse("FALSE") // fails

This solution is not concise enough:

这个解决方案不够简洁:

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

I am working on solving this exact problem for Typecast.js. And the best solution to all three objectives is this one:

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

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

It works for many cases, does not fail when values like {} are passed in, and is very concise. Also it returns false as the default value rather than undefined or throwing an Error, which is more useful in loosely-typed Javascript development. Bravo to the other answers that suggested it!

它适用于许多情况,在传入的值(比如{})时不会失败,而且非常简洁。同样,它返回false作为默认值,而不是未定义或抛出错误,这在松散类型的Javascript开发中更有用。对其他的答案来说,太棒了!

#24


7  

another solution. jsFiddle

另一个解决方案。jsFiddle

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

test cases run in node

测试用例在节点中运行。

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

#25


6  

You need to separate (in your thinking) the value of your selections and the representation of that value.

您需要将选择的值和该值的表示分开(在您的思想中)。

Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)

在JavaScript逻辑中选择一个点,它们需要从字符串哨兵转换为本地类型,并在那里进行比较,最好是在需要转换的每个值上只执行一次。记住,如果字符串sentinel不是脚本所知道的(即默认为true或false),则需要处理什么情况。

In other words, yes, you need to depend on the string's value. :-)

换句话说,是的,您需要依赖于字符串的值。:-)

#26


6  

I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/filthy-ness but includes "false" as an acceptible value for false.

我有点晚了,但是我有一个小片段来做这个,它实际上维护了所有的jscript truthey/falsey/filthy-ness,但是包括“false”作为一个可接受的false值。

I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.

我更喜欢这种方法,因为它不依赖于第三方来解析代码(我。e: eval/JSON.parse),这在我的头脑中是多余的,它足够短,不需要一个实用程序函数,并且维护其他的truthey/falsey约定。

var value = "false";
var result = (value == "false") != Boolean(value);

// value = "true"  => result = true
// value = "false" => result = false
// value = true    => result = true
// value = false   => result = false
// value = null    => result = false
// value = []      => result = true
// etc..

#27


5  

function parseBool(value) {
    if (typeof value === "boolean") return value;

    if (typeof value === "number") {
        return value === 1 ? true : value === 0 ? false : undefined;
    }

    if (typeof value != "string") return undefined;

    return value.toLowerCase() === 'true' ? true : false;
}

#28


5  

I wrote a function to match PHP's filter_var which does this nicely. Available in a gist: https://gist.github.com/CMCDragonkai/7389368

我编写了一个函数来匹配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;
};

#29


5  

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

If you are not sure of the input, the above works for boolean and as well any string.

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

#30


4  

I've found that using '1' and an empty value '' for boolean values works far more predictably than 'true' or 'false' string values... specifically with html forms since uninitialized/empty values in Dom elements will consistently evaluate to false whereas any value within them evaluates to true.

我发现,使用'1'和一个空值'用于布尔值,比'true'或'false' string值更容易预测……特别是html表单,因为Dom元素中的未初始化/空值将始终对错误进行评估,而其中的任何值都将计算为true。

For instance:

例如:

<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>

Just seemed like an easier road, so far it's been very consistent/easy... perhaps someone can determine a way to break this?

就像一条更容易的路,到目前为止,它是非常一致/容易的……也许有人能决定一种方法来打破这种局面?