简体   繁体   English

如何在 JavaScript 中将字符串转换为 boolean?

[英]How can I convert a string to boolean in JavaScript?

Can I convert a string representing a boolean value (eg, 'true', 'false') into a intrinsic type in JavaScript?我可以将表示 boolean 值(例如,'true'、'false')的字符串转换为 JavaScript 中的固有类型吗?

I have a hidden form in HTML that is updated based upon a user's selection within a list.我在 HTML 中有一个隐藏表单,它根据用户在列表中的选择进行更新。 This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value.此表单包含一些表示 boolean 值的字段,并动态填充了一个固有的 boolean 值。 However, once this value is placed into the hidden input field it becomes a string.但是,一旦将此值放入隐藏的输入字段中,它就会变成一个字符串。

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.在将字段转换为字符串后,我能找到的确定该字段的 boolean 值的唯一方法是取决于其字符串表示形式的字面值。

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

Is there a better way to accomplish this?有没有更好的方法来完成这个?

Do:做:

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

using the identity operator ( === ), which doesn't make any implicit type conversions when the compared variables have different types.使用恒等运算符 ( === ),当比较变量具有不同类型时,它不会进行任何隐式类型转换。

This will set isTrueSet to a boolean true if the string is "true" and boolean false if it is string "false" or not set at all.如果字符串为“true”,则将isTrueSet设置为布尔值true ;如果字符串为“false”或根本未设置,则设置为布尔值false


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.任何不是空字符串的字符串都将通过使用它们来评估为true Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.尽管它们是我能想到的关于布尔转换的最简洁的方法,但我认为它们不是您想要的。

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" .这个高度赞成的遗留答案在技术上是正确的,但只涵盖了一个非常具体的场景,当您的字符串值为 EXACTLY "true""false"时。

An invalid json string passed into these functions below WILL throw an exception .传递给下面这些函数的无效 json 字符串将引发异常


Original answer:原答案:

How about?怎么样?

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

or with jQuery或使用 jQuery

$.parseJSON("TRUE".toLowerCase());
const stringToBoolean = (stringValue) => {
    switch(stringValue?.toLowerCase()?.trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
        case undefined:
          return false;

        default: 
          return JSON.parse(stringValue);
    }
}

I think this is much universal:我认为这是非常普遍的:

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

It goes:它去:

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

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.这评估为真/假。

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 clashing with other code that extends the String object:对于那些想要扩展 String 对象来获得它但担心可枚举性并担心与扩展 String 对象的其他代码冲突的人(参见注释):

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 显示为 false,而 Opera、Chrome、Safari 和 IE 显示为 true。错误 720760

This is the easiest way to do boolean conversion I came across recently.这是我最近遇到的最简单的布尔转换方法。 Thought of adding it.想加上它。

JSON.parse('true');

 let trueResponse = JSON.parse('true'); let falseResponse = JSON.parse('false'); console.log(trueResponse); console.log(falseResponse);

Wood-eye be careful.木眼要小心。 After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:在应用获得 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]));}

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.我认为@Steven 的答案是最好的答案,并且处理的情况比传入值只是一个字符串要多得多。 I wanted to extend it a bit and offer the following:我想对其进行一些扩展并提供以下内容:

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.如果您已经知道您必须考虑的所有true案例,则无需涵盖所有false案例。 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您可以将任何可以传递为true值的东西传递给此方法(或添加其他值,这非常简单),其他所有内容都将被视为false

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/我还创建了小提琴来测试它http://jsfiddle.net/remunda/2GRhG/

Your solution is fine.你的解决方案很好。

Using === would just be silly in this case, as the field's value will always be a String .在这种情况下使用===会很愚蠢,因为该字段的value将始终是String

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 ,为每个真实值返回true ,除了'false''f''no''n''0' (不区分大小写)。

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

The Boolean object doesn't have a 'parse' method.布尔对象没有“解析”方法。 Boolean('false') returns true, so that won't work. Boolean('false')返回 true,所以这不起作用。 !!'false' also returns true , so that won't work also. !!'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() .如果您希望 string 'true'返回 boolean true并 string 'false'返回 boolean false ,那么最简单的解决方案是使用eval() eval('true') returns true and eval('false') returns false. eval('true')返回 true 并且eval('false')返回 false。 Keep in mind the performance implications when using eval() though.请记住使用eval()时的性能影响。

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,826,922
  2. Switch case on Bool object : 2,825,469 Bool 对象上的开关盒:2,825,469
  3. Casting to JSON : 1,867,774转换为 JSON :1,867,774
  4. !! !! conversions : 805,322转化次数:805,322
  5. Prototype of String : 713,637字符串原型:713,637

They are linked to the related answer where you can find more information (pros and cons) about each one;它们链接到相关答案,您可以在其中找到有关每个答案的更多信息(优点和缺点); specially in the comments.特别是在评论中。

这是从接受的答案中得出的,但实际上它有一个非常薄弱的​​地方,我很震惊它是如何获得赞成票的,它的问题是你必须考虑字符串的大小写,因为这是区分大小写的

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

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”之外,此函数执行通常的布尔强制转换。

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
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.");
  }
};

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

Simplest solution 🙌🏽最简单的解决方案🙌🏽

with ES6+使用 ES6+

use the logical NOT twice [ !!使用逻辑 NOT两次[ !! ] to get the string converted ]获取转换后的字符串

Just paste this expression...只需粘贴此表达式...

const stringToBoolean = (string) => string === 'false' ? false : !!string

And pass your string to it!并将您的字符串传递给它!

stringToBoolean('')                 // false
stringToBoolean('false')            // false
stringToBoolean('true')             // true
stringToBoolean('hello my friend!') // true
🤙🏽 Bonus! 🤙🏽 奖金! 🤙🏽 🤙🏽
 const betterStringToBoolean = (string) => string === 'false' || string === 'undefined' || string === 'null' || string === '0' ? false : !!string

You can include other strings at will to easily extend the usage of this expression...:您可以随意包含其他字符串以轻松扩展此表达式的用法...:

 betterStringToBoolean('undefined') // false betterStringToBoolean('null') // false betterStringToBoolean('0') // false betterStringToBoolean('false') // false betterStringToBoolean('') // false betterStringToBoolean('true') // true betterStringToBoolean('anything else') // true

To convert both string("true", "false") and boolean to boolean将 string("true", "false") 和 boolean 都转换为 boolean

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

Where flag can be flag可以在哪里

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

you can use JSON.parse as follows:你可以使用JSON.parse如下:

 var trueOrFalse='True'; result =JSON.parse(trueOrFalse.toLowerCase()); if(result==true) alert('this is true'); else alert('this is false');

in this case .toLowerCase is important在这种情况下.toLowerCase很重要

This function can handle string as well as Boolean true/false.此函数可以处理字符串以及布尔值 true/false。

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

Demonstration below:下面的演示:

 function stringToBoolean(val) { var a = { 'true': true, 'false': false }; return a[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("============================================="); // what if value was undefined? console.log("undefined result: " + stringToBoolean(undefined)); console.log("type of undefined result: " + typeof(stringToBoolean(undefined))); console.log("============================================="); // what if value was an unrelated string? console.log("unrelated string result: " + stringToBoolean("hello world")); console.log("type of unrelated string result: " + typeof(stringToBoolean(undefined)));

I'm suprised that includes was not suggested我很惊讶不建议includes

let bool = "false"
bool = !["false", "0", 0].includes(bool)

You can modify the check for truely or include more conditions (eg null , '' ).您可以修改检查是否为 true 或包含更多条件(例如null'' )。

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"

One Liner一个班轮

We just need to account for the "false" string since any other string (including "true") is already true .我们只需要考虑“false”字符串,因为任何其他字符串(包括“true”)已经是true

function b(v){ return v==="false" ? false : !!v; }

Test测试

b(true)    //true
b('true')  //true
b(false)   //false
b('false') //false

A more exaustive version更详尽的版本

function bool(v){ return v==="false" || v==="null" || v==="NaN" || v==="undefined" || v==="0" ? false : !!v; }

Test测试

bool(true)        //true
bool("true")      //true
bool(1)           //true
bool("1")         //true
bool("hello")     //true

bool(false)       //false
bool("false")     //false
bool(0)           //false
bool("0")         //false
bool(null)        //false
bool("null")      //false
bool(NaN)         //false
bool("NaN")       //false
bool(undefined)   //false
bool("undefined") //false
bool("")          //false

bool([])          //true
bool({})          //true
bool(alert)       //true
bool(window)      //true

why don't you try something like this你为什么不试试这样的东西

Boolean(JSON.parse((yourString.toString()).toLowerCase()));

It will return an error when some other text is given rather than true or false regardless of the case and it will capture the numbers also as无论情况如何,当给出其他文本而不是真或假时,它将返回错误,并且它还将捕获数字作为

// 0-> false
// any other number -> true

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.在 JavaScript 逻辑中选择一个点,他们需要从字符串标记转换为原生类型并在那里进行比较,最好是对每个需要转换的值只进行一次比较。 Remember to address what needs to happen if the string sentinel is not one the script knows (ie do you default to true or to false?)如果字符串 sentinel 不是脚本知道的字符串,请记住解决需要发生的情况(即,您默认为 true 还是 false?)

In other words, yes, you need to depend on the string's value.换句话说,是的,您需要依赖字符串的值。 :-) :-)

Like @Shadow2531 said, you can't just convert it directly.就像@Shadow2531 说的,你不能直接转换它。 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.如果您的代码将被其他人重用/使用,我还建议您考虑除 "true" 和 "false" 之外的字符串输入,它们是 'truthy' 和 'falsey'。 This is what I use:这就是我使用的:

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

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.我有点晚了,但是我有一个小片段可以做到这一点,它基本上维护了所有 JScripts 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 (ie: 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.我更喜欢这种方法而不是提到的方法,因为它不依赖第 3 方来解析代码(即:eval/JSON.parse),这在我看来是多余的,它足够短,不需要实用程序函数并维护其他真/假约定。

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

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
> 

Holy god some of these answers are just wild.天哪,其中一些答案很疯狂。 I love JS and its infinite number of ways to skin a bool.我喜欢 JS 和它无数种剥皮布尔值的方法。

My preference, which I was shocked not to see already, is:我很震惊地没有看到我的偏好是:

testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;

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!对于这些类型的转换,请始终使用 === 运算符而不是 == 运算符!

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.为真值和假值返回真/假,但也为多个字符串值返回真/假,如果它们是布尔值而不是字符串,则它们将是真或假。
  • 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.使用 JSON 的问题在于它会因导致 Javascript 错误而失败。 This solution is not resilient (though it satisfies 1 and 3):该解决方案没有弹性(尽管它满足 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 .我正在为Typecast.js解决这个确切的问题。 And the best solution to all three objectives is this one:这三个目标的最佳解决方案是:

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.它还返回 false 作为默认值,而不是 undefined 或抛出错误,这在松散类型的 Javascript 开发中更有用。 Bravo to the other answers that suggested it!对建议它的其他答案表示赞许!

I wrote a function to match PHP's filter_var which does this nicely.我写了一个函数来匹配 PHP 的 filter_var ,它很好地做到了这一点。 Available in a gist: https://gist.github.com/CMCDragonkai/7389368提供要点: 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;
};

The simplest way which I always use:我一直使用的最简单的方法:

let value = 'true';
let output = value === 'true';
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;
}

Lots of fancy answers here.这里有很多花哨的答案。 Really surprised no one has posted this solution:真的很惊讶没有人发布这个解决方案:

var booleanVal = toCast > '';

This resolves to true in most cases other than bool false, number zero and empty string (obviously).在大多数情况下,这解析为 true,而不是 bool false、数字零和空字符串(显然)。 You can easily look for other falsey string values after the fact eg:您可以在事后轻松查找其他虚假字符串值,例如:

var booleanVal = toCast > '' && toCast != 'false' && toCast != '0';  
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.如果您不确定输入,则上述内容适用于布尔值以及任何字符串。

If you are certain that the test subject is always a string, then explicitly checking that it equals true is your best bet.如果您确定测试主题始终是一个字符串,那么明确检查它是否等于true是您最好的选择。

You may want to consider including an extra bit of code just in case the subject could actually a boolean.您可能需要考虑包含一些额外的代码,以防主题实际上是布尔值。

var isTrueSet =
    myValue === true ||
    myValue != null &&
    myValue.toString().toLowerCase() === 'true';

This could save you a bit of work in the future if the code gets improved/refactored to use actual boolean values instead of strings.如果代码得到改进/重构以使用实际的布尔值而不是字符串,这可以在将来为您节省一些工作。

The most simple way is最简单的方法是

a = 'True';
a = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;

@guinaps> Any string which isn't the empty string will evaluate to true by using them. @guinaps> 任何不是空字符串的字符串都将通过使用它们来评估为真。

How about using the String.match() method如何使用 String.match() 方法

var str="true";
var boolStr=Boolean(str.match(/^true$/i)); 

this alone won't get the 1/0 or the yes/no, but it will catch the TRUE/true, as well, it will return false for any string that happens to have "true" as a substring.仅此一项不会得到 1/0 或是/否,但它会捕获 TRUE/true,同样,对于碰巧将“true”作为子字符串的任何字符串,它将返回 false。

EDIT编辑

Below is a function to handle true/false, 1/0, yes/no (case-insensitive)下面是处理真/假、1/0、是/否(不区分大小写)的函数

​function stringToBool(str) {
    var bool;
    if (str.match(/^(true|1|yes)$/i) !== null) {
        bool = true;
    } else if (str.match(/^(false|0|no)*$/i) !== null) {
        bool = false;
    } else {
        bool = null;
        if (console) console.log('"' + str + '" is not a boolean value');
    }
    return bool;
}

stringToBool('1'); // true
stringToBool('No'); // false
stringToBool('falsey'); // null ("falsey" is not a boolean value.)
stringToBool(''); // false

I do this, which will handle 1=TRUE=yes=YES=true, 0=FALSE=no=NO=false:我这样做,它将处理 1=TRUE=yes=YES=true, 0=FALSE=no=NO=false:

BOOL=false
if (STRING)
  BOOL=JSON.parse(STRING.toLowerCase().replace('no','false').replace('yes','true'));

Replace STRING with the name of your string variable.将 STRING 替换为您的字符串变量的名称。

If it's not null, a numerical value or one of these strings: "true", "TRUE", "false", "FALSE", "yes", "YES", "no", "NO" It will throw an error (intentionally.)如果不为 null,则为数值或以下字符串之一:“true”、“TRUE”、“false”、“FALSE”、“yes”、“YES”、“no”、“NO” 会抛出错误(故意地。)

I use an own method which includes a check if the object exists first and a more intuitive conversion to boolean:我使用自己的方法,其中包括首先检查对象是否存在以及更直观地转换为布尔值:

function str2bool(strvalue){
  return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);
}

The results are:结果是:

var test; // false
var test2 = null; // false
var test3 = 'undefined'; // false
var test4 = 'true'; // true
var test5 = 'false'; // false
var test6 = true; // true
var test7 = false; // false
var test8 = 1; // true
var test9 = 0; // false
var test10 = '1'; // true
var test11 = '0'; // false

Fiddle: http://jsfiddle.net/av5xcj6s/小提琴:http: //jsfiddle.net/av5xcj6s/

In nodejs by using node-boolify it is possible在 nodejs 中使用node-boolify是可能的

Boolean Conversion Results布尔转换结果

Boolify(true); //true
Boolify('true'); //true
Boolify('TRUE'); //null
Boolify(1); //true
Boolify(2); //null
Boolify(false); //false
Boolify('false'); //false
Boolify('FALSE'); //null
Boolify(0); //false
Boolify(null); //null
Boolify(undefined); //null
Boolify(); //null
Boolify(''); //null
/// 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

 const boolTrue = JSON.parse("true") const boolFalse = JSON.parse("false") console.log(boolTrue) // true console.log(boolFalse) // false

To convert string boolean like "true" to actually boolean value is just wrapping to JSON.parse() example: JSON.parse("true")将字符串布尔值(如“true”)转换为实际的布尔值只是包装到JSON.parse()示例: JSON.parse("true")

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' 字符串值更可预测......特别是对于 html 表单,因为 Dom 元素中的未初始化/空值将始终评估为假,而其中的任何值都为真。

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?似乎是一条更容易的道路,到目前为止它一直非常一致/容易......也许有人可以确定一种方法来打破这个?

i wrote a helper function that handles your cases (and some more).我写了一个辅助函数来处理你的案例(以及更多)。 Feel free to alter it to your specific needs随意更改它以满足您的特定需求

/**
 * @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);
};

Here is my 1 liner submission: I needed to evaluate a string and output, true if 'true', false if 'false' and a number if anything like '-12.35673'.这是我的 1 班轮提交:我需要评估一个字符串和输出,如果为“真”则为真,如果为“假”则为假,如果类似“-12.35673”则为数字。

val = 'false';

val = /^false$/i.test(val) ? false : ( /^true$/i.test(val) ? true : val*1 ? val*1 : val );

Simple solution i have been using it for a while简单的解决方案我已经使用了一段时间

function asBoolean(value) {

    return (''+value) === 'true'; 

}


// asBoolean(true) ==> true
// asBoolean(false) ==> false
// asBoolean('true') ==> true
// asBoolean('false') ==> false

If there's some other code that's converting the boolean value to a string, you need to know exactly how that code stores true/false values.如果有一些其他代码将布尔值转换为字符串,您需要确切地知道该代码如何存储真/假值。 Either that or you need to have access to a function that reverses that conversion.要么,要么您需要访问一个反转该转换的函数。

There are infinitely many ways to represent boolean values in strings ("true", "Y", "1", etc.).有无数种方法可以在字符串中表示布尔值(“true”、“Y”、“1”等)。 So you shouldn't rely on some general-purpose string-to-boolean converter, like Boolean(myValue).所以你不应该依赖一些通用的字符串到布尔转换器,比如 Boolean(myValue)。 You need to use a routine that reverses the original boolean-to-string conversion, whatever that is.无论是什么,您都需要使用一个反转原始布尔到字符串转换的例程。

If you know that it converts true booleans to "true" strings, then your sample code is fine.如果您知道它将真正的布尔值转换为“真正的”字符串,那么您的示例代码就可以了。 Except that you should use === instead of ==, so there's no automatic type conversion.除了你应该使用 === 而不是 ==,所以没有自动类型转换。

The fastest safe way to convert a string to a boolean in one line of code在一行代码中将字符串转换为布尔值的最快安全方法

One of features that help to fasten the code execution in Javascript is Short-Circuit Evaluation :有助于加快 Javascript 代码执行的功能之一是Short-Circuit Evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:由于逻辑表达式是从左到右评估的,因此使用以下规则测试它们是否存在可能的“短路”评估:

  • false && (anything) is short-circuit evaluated to false. false && (anything) 短路评估为 false。
  • true ||真 || (anything) is short-circuit evaluated to true. (anything) 短路评估为真。

So that if you want to test a string value for being true of false in JSON.parse way of test and keep the performance strong, you may use the ||因此,如果您想在false JSON.parse true强大的性能,您可以使用|| operator to exclude the slow code from execution in case the test value is of boolean type.如果测试值是布尔类型,则运算符将慢速代码排除在执行之外。

test === true || ['true','yes','1'].indexOf(test.toString().toLowerCase()) > -1

As the Array.prototype.indexOf() method is a part of ECMA-262 standard in the 5th edition, you may need a polyfill for the old browsers support.由于Array.prototype.indexOf()方法是ECMA-262第 5 版标准的一部分,您可能需要一个polyfill来支持旧浏览器。

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let O be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of O with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}
function isTrue(val) {
    try {
        return !!JSON.parse(val);
    } catch (e) {
        return false;
    }
}

I use this simple approach (using "myVarToTest"):我使用这种简单的方法(使用“myVarToTest”):

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

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

Take it easy using this lib.轻松使用这个库。

https://github.com/rohmanhm/force-boolean https://github.com/rohmanhm/force-boolean

you just need to write a single line你只需要写一行

const ForceBoolean = require('force-boolean')

const YOUR_VAR = 'false'
console.log(ForceBoolean(YOUR_VAR)) // it's return boolean false

It's also support for following也支持关注

 return false if value is number 0
 return false if value is string '0'
 return false if value is string 'false'
 return false if value is boolean false
 return true if value is number 1
 return true if value is string '1'
 return true if value is string 'true'
 return true if value is boolean true

Here is simple function that will do the trick,这是一个简单的函数,可以解决问题,

   function convertStringToBool(str){
        return ((str === "True") || (str === "true")) ? true:false;
    }

This will give the following result这将给出以下结果

convertStringToBool("false") //returns false
convertStringToBool("true") // returns true
convertStringToBool("False") // returns false
convertStringToBool("True") // returns true

I'm using this one when I get value from URL/Form or other source.当我从 URL/Form 或其他来源获得价值时,我正在使用这个。

It is pretty universal one line piece of code.这是非常通用的一行代码。

Maybe not the best for performance, if you need to run it millions times let me know, we can check how to optimize it, otherwise is pretty good and customizable.也许不是最好的性能,如果您需要运行它数百万次,请告诉我,我们可以检查如何优化它,否则非常好并且可定制。

boolResult = !(['false', '0', '', 'undefined'].indexOf(String(myVar).toLowerCase().trim()) + 1);

Result:结果:

myVar = true;  // true
myVar = 'true';  // true
myVar = 'TRUE';  // true
myVar = '1';  // true
myVar = 'any other value not related to false';  // true

myVar = false; // false
myVar = 'false';  // false
myVar = 'FALSE';  // false
myVar = '0';  // false

For TypeScript we can use the function:对于 TypeScript,我们可以使用以下函数:

export function stringToBoolean(s: string, valueDefault: boolean = false): boolean {
    switch(s.toLowerCase())
    {
        case "true":
        case "1":
        case "on":
        case "yes":
        case "y":
            return true;

        case "false":
        case "0":
        case "off":
        case "no":
        case "n":
            return false;
    }

    return valueDefault;
}

Try this solution (it works like a charm!):试试这个解决方案(它就像一个魅力!):

function convertStrToBool(str)
    {
        switch(String(str).toLowerCase())
            {
                case 'undefined': case 'null': case 'nan': case 'false': case 'no': case 'f': case 'n': case '0': case 'off': case '':
                    return false;
                    break;
                default:
                    return true;
            };
    };

Many of the existing answers use an approach that is semantically similar to this, but I think there is value in mentioning that the following "one liner" is often sufficient.许多现有的答案使用与此语义相似的方法,但我认为值得一提的是,以下“一个衬里”通常就足够了。 For example, in addition to the OP's case (strings in a form) one often wants to read environment variables from process.env in NodeJS (whose values, to the best of my knowledge, are always strings) in order to enable or disable certain behaviors, and it is common for these to have the form SOME_ENV_VAR=1 .例如,除了 OP 的情况(表单中的字符串)之外,通常还希望从NodeJS中的process.env读取环境变量(据我所知,其值始终是字符串)以启用或禁用某些行为,并且这些行为通常具有SOME_ENV_VAR=1的形式。

const toBooleanSimple = (input) => 
  ['t', 'y', '1'].some(truePrefix => truePrefix === input[0].toLowerCase());

A slightly more robust and expressive implementation might look like this:稍微更健壮和更具表现力的实现可能如下所示:

/**
 * Converts strings to booleans in a manner that is less surprising
 * to the non-JS world (e.g. returns true for "1", "yes", "True", etc.
 * and false for "0", "No", "false", etc.)
 * @param input
 * @returns {boolean}
 */
function toBoolean(input) {
  if (typeof input !== 'string') {
    return Boolean(input);
  }
  const s = input.toLowerCase();
  return ['t', 'y', '1'].some(prefix => s.startsWith(prefix));
}

A (jest) unit test for this might look like this:对此的(开玩笑)单元测试可能如下所示:

describe(`toBoolean`, function() {
  const groups = [{
    inputs: ['y', 'Yes', 'true', '1', true, 1],
    expectedOutput: true
  }, {
    inputs: ['n', 'No', 'false', '0', false, 0],
    expectedOutput: false
  }]
  for (let group of groups) {
    for (let input of group.inputs) {
      it(`should return ${group.expectedOutput} for ${JSON.stringify(input)}`, function() {
        expect(toBoolean(input)).toEqual(group.expectedOutput);
      });
    }      
  }
});

It would be great if there was a function on the String object that did this for us, but we can easily add our own prototypes to extend the String object.如果 String 对象上有一个函数可以为我们执行此操作,那就太好了,但我们可以轻松添加自己的原型来扩展 String 对象。

Add this code somewhere in your project before you use it.在您使用它之前,将此代码添加到您的项目中的某处。

String.prototype.toBoolean = function() {
   return String(this.valueOf()).toLowerCase() === true.toString();
};

Try it out like this:试试这样:

var myValue = "false"
console.log("Bool is " + myValue.toBoolean())
console.log("Bool is " + "False".toBoolean())
console.log("Bool is " + "FALSE".toBoolean())
console.log("Bool is " + "TRUE".toBoolean())
console.log("Bool is " + "true".toBoolean())
console.log("Bool is " + "True".toBoolean())

So the result of the original question would then be:因此,原始问题的结果将是:

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue.toBoolean();
if (String(a) == "true"){
  //true block
} else {
  //false block
}

我一直在使用这个片段来转换数字和布尔值:

var result = !isNaN(value) ? parseFloat(value) : /^\s*(true|false)\s*$/i.exec(value) ? RegExp.$1.toLowerCase() === "true" : value;

Building on Steven's answer above, I wrote this function as a generic parser for string input:基于上面 Steven 的回答,我编写了这个函数作为字符串输入的通用解析器:

parse:
  function (value) {
    switch (value && value.toLowerCase()) {
      case null: return null;
      case "true": return true;
      case "false": return false;
      default: try { return parseFloat(value); } catch (e) { return value; }
    }
  }
    MyLib.Convert.bool = function(param) {
         var res = String(param).toLowerCase();
         return !(!Boolean(res) || res === "false" || res === "0");
     }; 

A lot of the existing answers are similar, but most ignore the fact that the given argument could also be an object.许多现有的答案都是相似的,但大多数都忽略了给定参数也可能是一个对象的事实。

Here is something I just whipped up:这是我刚刚整理的东西:

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

...and the unit test for it ...以及它的单元测试

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

A shorter way to write this, could be var isTrueSet = (myValue === "true") ? true : false;写这个的更短的方法可能是var isTrueSet = (myValue === "true") ? true : false; var isTrueSet = (myValue === "true") ? true : false; Presuming only "true" is true and other values are false.假设只有“真”为真,其他值为假。

To evaluate both boolean and boolean-like strings like boolean I used this easy formula:为了评估布尔值和类似布尔值的字符串,我使用了这个简单的公式:

var trueOrStringTrue = (trueOrStringTrue === true) || (trueOrStringTrue === 'true');

As is apparent, it will return true for both true and 'true'.很明显,它会为 true 和 'true' 返回 true。 Everything else returns false.其他一切都返回假。

Take care, maybe in the future the code change and return boolean instead of one string at the moment.请注意,也许将来代码会更改并返回布尔值而不是此时的一个字符串。

The solution would be:解决方案是:

//Currently
var isTrue = 'true';
//In the future (Other developer change the code)
var isTrue = true;
//The solution to both cases
(isTrue).toString() == 'true'

WARNING: Never use this method for untrusted input, such as URL parameters.警告:切勿将此方法用于不受信任的输入,例如 URL 参数。

You can use the eval() function.您可以使用eval()函数。 Directly pass your string to eval() function.直接将您的字符串传递给eval()函数。

 console.log(eval('true'), typeof eval('true')) console.log(eval('false'), typeof eval('false'))

function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayır": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}

The shorthand of Boolean(value) is !!value, this is because ! Boolean(value) 的简写是 !!value,这是因为 ! converts a value to the opposite of what it currently is, and then !将值转换为与当前值相反的值,然后 ! reverses it again back to original form.再次将其反转回原始形式。

Boolean.parse() does exist in some browser implementations. Boolean.parse()确实存在于某些浏览器实现中。 It's definitely not universal, so if that's something that you need than you shouldn't use this method.它绝对不是通用的,所以如果这是你需要的东西,那么你不应该使用这种方法。 But in Chrome, for example (I'm using v21) it works just fine and as one would expect.但在 Chrome 中,例如(我使用的是 v21)它工作得很好,正如人们所期望的那样。

You even do not need to convert the string to boolean.您甚至不需要将字符串转换为布尔值。 just use the following: var yourstring = yourstringValue == 1 ? true : false;只需使用以下内容: var yourstring = yourstringValue == 1 ? true : false; var yourstring = yourstringValue == 1 ? true : false;

To Get Boolean values from string or number Here is good solution:从字符串或数字中获取布尔值这是一个很好的解决方案:

var boolValue = Boolean(Number('0'));

var boolValue = Boolean(Number('1'));

First will return false and second will return true .第一个将返回false ,第二个将返回true

var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1) ? true : false;

or even just甚至只是

var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1);

Similar to some of the switch statements but more compact.类似于一些 switch 语句,但更紧凑。 The value returned will only be true if the string is one of the trueVals strings.仅当字符串是 trueVals 字符串之一时,返回的值才会为真。 Everything else is false.其他一切都是假的。 Of course, you might want to normalise the input string to make it lower case and trim any spaces.当然,您可能希望规范化输入字符串以使其小写并修剪任何空格。

Convert String to Boolean将字符串转换为布尔值

var vIn = "true";
var vOut = vIn.toLowerCase()=="true"?1:0;

Convert String to Number将字符串转换为数字

var vIn = 0;
var vOut = parseInt(vIn,10/*base*/);

I hope this is a most comprehensive use case我希望这是一个最全面的用例

function parseBoolean(token) {
  if (typeof token === 'string') {
    switch (token.toLowerCase()) {
      case 'on':
      case 'yes':
      case 'ok':
      case 'ja':
      case 'да':
      // case '':
      // case '':
        token = true;
        break;
      default:
        token = false;
    }
  }
  let ret = false;
  try {
    ret = Boolean(JSON.parse(token));
  } catch (e) {
    // do nothing or make a notification
  }
  return ret;
}

In HTML the values of attributes eventually become strings.在 HTML 中,属性的值最终会变成字符串。 To mitigate that in undesired situations you can have a function to conditionally parse them into values they represent in the JavaScript or any other programming langauge of interest.为了在不希望的情况下减轻这种情况,您可以使用一个函数有条件地将它们解析为它们在 JavaScript 或任何其他感兴趣的编程语言中表示的值。

Following is an explanation to do it for reviving boolean type from the string type, but it can be further expanded into other data types too, like numbers, arrays or objects.以下是从字符串类型恢复布尔类型的解释,但它也可以进一步扩展到其他数据类型,如数字、数组或对象。

In addition to that JSON.parse has a revive parameter which is a function.除此之外 JSON.parse 有一个revive 参数,它是一个函数。 It also can be used to achieve the same.它也可以用来实现相同的目的。

Let's call a string looking like a boolean , "true", a boolean string likewise we can call a string like a number, "1", a number string .让我们称一个看起来像boolean的字符串 "true" 是一个boolean 字符串,同样我们也可以称一个像数字的字符串 "1" 是一个数字字符串 Then we can determine if a string is a boolean string :然后我们可以确定一个字符串是否为布尔字符串

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

After that we need to parse the boolean string as JSON by JSON.parse method:之后,我们需要通过JSON.parse方法将布尔字符串解析为 JSON:

JSON.parse(aBooleanString);

However, any string that is not a boolean string , number string , or any stringified object or array (any invalid JSON) will cause the JSON.parse method to throw a SyntaxError .但是,任何不是boolean stringnumber string或任何字符串化对象或数组(任何无效 JSON)的字符串都将导致JSON.parse方法抛出SyntaxError

So, you will need to know with what to call it, ie if it is a boolean string .因此,您将需要知道如何调用它,即它是否为布尔字符串 You can achieve this by writing a function that makes the above defiend boolean string check and call JSON.parse :您可以通过编写一个函数来检查上述defiend布尔字符串并调用JSON.parse来实现这一点:

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

One can further generalize the isBooleanString utility to have a more broader perspective on what qualifies as a boolean string by further parametrizing it to accept an optional array of accepted boolean strings:可以进一步概括isBooleanString实用程序,通过进一步参数化它以接受可接受的布尔字符串的可选数组,从而更广泛地了解什么是布尔字符串:

const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) => spec.some(item => item === string);
const result: Boolean = strValue === "true" ? true : false

Use an if statment:使用if语句:

 function parseBool(str) { if (str.toLowerCase() == 'true') { var val = true; } else if (str.toLowerCase() == 'false') { var val = false; } else { //If it is not true of false it returns undefined.// var val = undefined; } return val; } console.log(parseBool(''), typeof parseBool('')); console.log(parseBool('TrUe'), typeof parseBool('TrUe')); console.log(parseBool('false'), typeof parseBool('false'));

你甚至不需要使用变量,如果你知道“真”总是小写,你可以使用它来返回真或假:

(eval(yourBooleanString == 'true'))

I think it can be done in 1 liner with a use arrow function我认为它可以用一个使用箭头功能在 1 班轮中完成

const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;

You guys can run and test various cases with following code snippet你们可以使用以下代码片段运行和测试各种案例

 const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false; console.log(convertStringToBoolean("a")); console.log(convertStringToBoolean(null)); console.log(convertStringToBoolean(undefined)); console.log(convertStringToBoolean("undefined")); console.log(convertStringToBoolean(true)); console.log(convertStringToBoolean(false)); console.log(convertStringToBoolean(0)); console.log(convertStringToBoolean(1)); // only case which will not work

The strongest way is the following because it also handle undefined case:最强的方法如下,因为它也处理未定义的情况:

    ({'true': true, 'false': false})[myValue];
    ({'true': true, 'false': false})[undefined] // => undefined
    ({'true': true, 'false': false})['true'] // => true
    ({'true': true, 'false': false})['false] // => false

if you are sure the input is anything only within 'true' and 'false' why not :如果您确定输入仅在“真”和“假”范围内,为什么不呢:

 let x = 'true' ; //let x = 'false'; let y = x === 'true' ? true : false; console.log(typeof(y), y);

ES6+ ES6+

 const string = "false" const string2 = "true" const test = (val) => (val === "true" || val === "True") console.log(test(string)) console.log(test(string2))

function returnBoolean(str){

    str=str.toString().toLowerCase();

    if(str=='true' || str=='1' || str=='yes' || str=='y' || str=='on' || str=='+'){
        return(true);
    }
    else if(str=='false' || str=='0' || str=='no' || str=='n' || str=='off' || str=='-'){
        return(false);
    }else{
        return(undefined);
    }
}

The following would be enough以下就足够了

String.prototype.boolean = function() {
    return "true" == this; 
};

"true".boolean() // returns true "false".boolean() // returns false

You can use Function to return a Boolean value from string "true" or "false"您可以使用Function从字符串"true""false"返回Boolean

 const TRUE_OR_FALSE = str => new Function(`return ${str}`)(); const [TRUE, FALSE] = ["true", "false"]; const [T, F] = [TRUE_OR_FALSE(TRUE), TRUE_OR_FALSE(FALSE)]; console.log(T, typeof T); // `true` `"boolean"` console.log(F, typeof F); // `false` `"boolean"`

The `toBoolean' function returns false for null, undefined, '', 'false'. `toBoolean' 函数为 null、undefined、''、'false' 返回 false。 It returns true for any other string:它为任何其他字符串返回 true:

const toBoolean = (bool) => {
  if (bool === 'false') bool = false
  return !!bool
}

toBoolean('false') // returns false

In typescript, a small function to handle if the value was passed as a string, number or a boolean eg 'true', 'false', true, false, 1, or 0.在 typescript 中,一个小的 function 用于处理该值是否作为字符串、数字或 boolean 例如“1”、“假”、“真”、“假”。

const getAsBoolean = (value: string | boolean | number) => {
  if (typeof value === 'string') {
    return value === 'true';
  } else if (typeof value === 'boolean' || typeof value === 'number') {
    return Boolean(value);
  } else {
    return undefined;
  }
};

If you are using Environment Variables, use the following.如果您使用的是环境变量,请使用以下内容。 Works on Heroku. Environment variables are string values that has to be converted to boolean values.适用于 Heroku。环境变量是必须转换为 boolean 值的字符串值。

// Create the database connection
    this.connection = new Sequelize({
      username: process.env.PG_USERNAME,
      password: process.env.PG_PASSWORD,
      database: process.env.PG_DATABASE,
      host: process.env.PG_HOST,
      port: process.env.PG_PORT,
      dialect: process.env.PG_DIALECT,
      dialectOptions: {
        ssl: {
          require: process.env.PG_DIALECT_OPTION_SSL_REQUIRED === 'true', // <<< convert from string to bool
          rejectUnauthorized:
            process.env.PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED === 'true', // <<< convert from string to bool
        },
      },
      logging: true,
    });

env file环境文件

# PostgreSQL Config
PG_USERNAME=ttubkcug
PG_PASSWORD=ea59cee2883e73c602e6c05b674cf16950d6a9f05ab
PG_DATABASE=d67potesdliv25
PG_HOST=ec2-23-333-45-192.compute-1.amazonaws.com
PG_PORT=5432
PG_DIALECT=postgres
PG_DIALECT_OPTION_SSL_REQUIRED=true
PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED=false

I use "eval"我使用“评估”

const value = "false"
const otherValue = "true"

console.log(eval(value)) // false
console.log(eval(otherValue)) // true
function parseBool(value: any, defaultsOnUndefined?: boolean) {
  if (['true', true, 1, '1', 'yes'].includes(value)) {
    return true;
  }
  if (['false', false, 0, '0', 'no', null].includes(value)) {
    return false;
  }
  return defaultsOnUndefined;
}

OR或者

function parseBool(value: any) {
  if (['true', true, 1, '1', 'yes'].includes(value)) {
    return true;
  }
  return false;
}

Simple one line operation if you need Boolean false and true from the string values:如果您需要字符串值中的布尔值falsetrue ,则简单的一行操作:

storeBooleanHere = stringVariable=="true"?true:false;
  • storeBooleanHere - This variable will hold the boolean value storeBooleanHere - 此变量将保存布尔值
  • stringVariable - Variable that has boolean stored as string stringVariable - 将布尔值存储为字符串的变量

I needed a code that converts any variable type into Boolean.我需要一个将任何变量类型转换为布尔值的代码。 Here's what I came up with:这是我想出的:

 const toBoolean = (x) => { if (typeof x === 'object') { for (var i in x) return true return false } return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase()) }

Let's test it!让我们测试一下!

 const toBoolean = (x) => { if (typeof x === 'object') { for (var i in x) return true return false } return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase()) } // Let's test it! let falseValues = [false, 'False', 0, '', 'off', 'no', [], {}, null, undefined] let trueValues = [ true, 'true', 'True', 1, -1, 'Any thing', ['filled array'], {'object with any key': null}] falseValues.forEach((value, index) => console.log(`False value ${index} of type ${typeof value}: ${value} -> ${toBoolean(value)}`)) trueValues.forEach((value, index) => console.log(`True value ${index} of type ${typeof value}: ${value} -> ${toBoolean(value)}`))

You can remove words like "off" and "no" from the array if they don't match your case.如果它们与您的情况不匹配,您可以从数组中删除诸如“off”和“no”之类的词。

var isTrueSet = eval(myValue); var isTrueSet = eval(myValue);

将字符串转换为布尔值的最简单方法如下:

Boolean(<stringVariable>)

works perfectly and very simple:完美且非常简单:

var boolean = "false";
boolean = (boolean === "true");

//boolean = JSON.parse(boolean); //or this way.. 

to test it:测试它:

 var boolean = "false"; boolean = (boolean === "true"); //boolean = JSON.parse(boolean); //or this way.. if(boolean == true){ alert("boolean = "+boolean); }else{ alert("boolean = "+boolean); }

// Try this in two ways convert a string to boolean // 尝试这两种方式将字符串转换为布尔值

    const checkBoolean = Boolean("false"); 
    const checkBoolean1 = !!"false";  
    
    console.log({checkBoolean, checkBoolean1});  

将字符串转换为布尔值的可能方法 I recommend you to create a function like the third option in the image and place it in a helper class as export, and reuse this function when you need.我建议您创建一个类似于图像中第三个选项的函数并将其作为导出放置在辅助类中,并在需要时重用此函数。

Just do a:只需做一个:

var myBool = eval (yourString);

Examples:例子:

alert (eval ("true") == true); // TRUE
alert (eval ("true") == false); // FALSE
alert (eval ("1") == true); // TRUE
alert (eval ("1") == false); // FALSE
alert (eval ("false") == true); // FALSE;
alert (eval ("false") == false); // TRUE
alert (eval ("0") == true); // FALSE
alert (eval ("0") == false); // TRUE
alert (eval ("") == undefined); // TRUE
alert (eval () == undefined); // TRUE

This method handles the empty string and undefined string naturally as if you declare a variable without assigning it a value.此方法自然地处理空字符串和未定义字符串,就好像您声明一个变量而不给它赋值一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM