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

发布于 2024-07-08 13:26:25 字数 350 浏览 7 评论 0原文

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

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

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

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

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

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

I have a hidden form in HTML that is updated based on 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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

寂寞陪衬 2024-07-15 13:26:26

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

更新(没有 JSON):

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

我还创建了小提琴来测试它 http://jsfiddle.net/remunda/2GRhG/

Universal solution with JSON parse:

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

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/

虫児飞 2024-07-15 13:26:26

你的解决方案很好。

在这种情况下,使用 === 会很愚蠢,因为字段的 value 将始终是 String

Your solution is fine.

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

人心善变 2024-07-15 13:26:26

布尔对象没有“解析”方法。 Boolean('false') 返回 true,所以这不起作用。 !!'false' 也会返回 true,所以这也不起作用。

如果您希望字符串 'true' 返回布尔值 true 和字符串 'false' 返回布尔值 false,那么最简单的解决方案是使用eval()eval('true') 返回 true,eval('false') 返回 false。

使用eval()时请记住性能和安全影响

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.

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 and security implications when using eval() though.

辞慾 2024-07-15 13:26:26
var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) { 
    return !falsy.test(val) && !!val;
};

这将为每个假值返回 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());
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
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());
椵侞 2024-07-15 13:26:26

答案有很多,很难选出一个。 就我而言,我在选择时会优先考虑性能,因此我创建了 这个 jsPerf 我希望它能带来一些启发这里。

结果简介(越高越好):

  1. 条件语句:2,826,922
  2. 在 Bool 对象上切换大小写:2,825,469
  3. 转换为 JSON:1,867,774
  4. !! 转换:805,322
  5. 字符串原型:713,637

它们是链接的到相关的答案,您可以在其中找到有关每个答案的更多信息(优点和缺点); 特别是在评论中。

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.

Brief of results (the higher the better):

  1. Conditional statement: 2,826,922
  2. Switch case on Bool object: 2,825,469
  3. Casting to JSON: 1,867,774
  4. !! conversions: 805,322
  5. Prototype of String: 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.

小…红帽 2024-07-15 13:26:26

这是取自已接受的答案,但实际上它有一个非常薄弱的​​点,我很惊讶它是如何获得这么多赞成票的,问题是你必须考虑字符串的大小写,因为这是区分大小写的

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

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');
喵星人汪星人 2024-07-15 13:26:26

我使用以下内容:

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

此函数执行通常的布尔强制转换,但字符串“false”(不区分大小写)和“0”除外。

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

一曲琵琶半遮面シ 2024-07-15 13:26:26

最简单的解决方案

Simplest solution ????????

with ES6+

use the logical NOT twice [ !! ] 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
ゝ杯具 2024-07-15 13:26:26

您要查找的表达式就像

/^true$/i.test(myValue)

This

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

tests myValue against a Regular expression 一样,不区分大小写,并且不会修改原型。

例子:

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

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.

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
深府石板幽径 2024-07-15 13:26:26

您可以使用 JSON.parse 如下:

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

在这种情况下 .toLowerCase 很重要

you can use JSON.parse as follows:

   
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

叹沉浮 2024-07-15 13:26:26

已经有很多答案了。 但以下内容在某些情况下可能很有用。

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

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

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

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

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
迷爱 2024-07-15 13:26:26

我很惊讶没有建议 includes

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

您可以修改 true 检查或包含更多条件(例如 null'')。

I'm suprised that includes was not suggested

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

You can modify the check for truely or include more conditions (e.g. null, '').

伪心 2024-07-15 13:26:26
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.");
  }
};
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.");
  }
};
风情万种。 2024-07-15 13:26:26

将 string("true", "false") 和 boolean 转换为 boolean

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

其中 flag 可以是

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

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

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

Where flag can be

 var flag = true
 var flag = "true"
 var flag = false
 var flag = "false"
梦屿孤独相伴 2024-07-15 13:26:26

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

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

演示如下:

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

This function can handle string as well as Boolean 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)));

梦冥 2024-07-15 13:26:26

One Liner

我们只需要考虑“false”字符串,因为任何其他字符串(包括“true”)都已经是true

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

测试

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

更详尽的版本

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

测试

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

One Liner

We just need to account for the "false" string since any other string (including "true") is already 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
﹉夏雨初晴づ 2024-07-15 13:26:26

我正在用这个

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"

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"
春庭雪 2024-07-15 13:26:26

你为什么不尝试这样的事情

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

当给出一些其他文本而不是 true 或 false 时,无论大小写,它都会返回一个错误,并且它也会捕获数字

// 0-> false
// any other number -> 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
陈甜 2024-07-15 13:26:26

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

在 JavaScript 逻辑中选择一个需要从字符串哨兵转换到本机类型的点,并在那里进行比较,最好只对每个需要转换的值进行一次比较。 请记住解决如果字符串哨兵不是脚本所知道的字符串(即您默认为 true 还是 false?)时需要发生的情况,

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

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

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

北恋 2024-07-15 13:26:26

另一个解决方案。 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
};

测试用例在节点中运行

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

another solution. 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
> 
明月松间行 2024-07-15 13:26:26

毫无疑问,最简单的方法(假设您的字符串为“true”或“false”)是:

var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to 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!

榕城若虚 2024-07-15 13:26:25

做法:

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

使用恒等运算符 (===),当比较的变量具有不同类型时,它不会进行任何隐式类型转换。

如果字符串为“true”,则将 isTrueSet 设置为布尔值 true;如果字符串为“false”或未设置,则将设置为布尔值 false全部。

为了使其不区分大小写,请尝试:

var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');

不要:

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

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

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

任何不是空字符串的字符串都将计算为 true 通过使用它们。 尽管它们是我能想到的关于布尔转换的最干净的方法,但我认为它们不是您正在寻找的。

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.

For making it case-insensitive, try:

var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === '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.

云巢 2024-07-15 13:26:25

警告

这个高度赞扬的遗留答案在技术上是正确的,但仅涵盖非常具体的场景,即当您的字符串值恰好是 "true""false" 时。

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


原答案:

怎么样?

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

或使用 jQuery

$.parseJSON("TRUE".toLowerCase());

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

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


Original answer:

How about?

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

or with jQuery

$.parseJSON("TRUE".toLowerCase());
陌伤浅笑 2024-07-15 13:26:25
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);
    }
}
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);
    }
}
晌融 2024-07-15 13:26:25

我认为这更通用:

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

它是:

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

I think this is much more universal:

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
甜尕妞 2024-07-15 13:26:25

记住要匹配大小写:

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

另外,如果是表单元素复选框,还可以检测该复选框是否被选中:

var isTrueSet = document.myForm.IS_TRUE.checked;

假设如果被选中,则“set”等于true。 这评估为真/假。

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.

夏雨凉 2024-07-15 13:26:25

这是我最近遇到的进行布尔转换的最简单方法。 想到了添加一下。

JSON.parse('true');

let trueResponse = JSON.parse('true');

let falseResponse = JSON.parse('false');

console.log(trueResponse);
console.log(falseResponse);

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

我很OK 2024-07-15 13:26:25

您可以使用正则表达式:

/*
 * 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' regardless
    // of capitalization and regardless of surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

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

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

alert("true".bool());

对于那些想要扩展 String 对象来获取此对象但担心可枚举性并担心与扩展的其他代码发生冲突的人(请参阅注释) String 对象:(

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

当然在旧版浏览器中不起作用,Firefox 显示 false,而 Opera、Chrome、Safari 和 IE 显示 true。错误 720760)

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' regardless
    // of capitalization and regardless of 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.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:

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)

画骨成沙 2024-07-15 13:26:25

木眼要小心。
在看到获得 500 多个赞成票的最佳答案后的后果后,我觉得有必要发布一些实际上有用的东西:

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

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

并以适当的、更宽容的方法结束:

var parseBool = function(str, strict) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)
    
    if (str == null)
    {
        if (strict)
            throw new Error("Parameter 'str' is null or undefined.");

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

测试:

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

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:

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, strict) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)
    
    if (str == null)
    {
        if (strict)
            throw new Error("Parameter 'str' is null or undefined.");

        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]));}
抽个烟儿 2024-07-15 13:26:25

我认为 @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;
    }
}

如果您已经知道必须考虑的所有 true 情况,则无需涵盖所有 false 情况为了。 您可以将任何可以传递 true 值的内容传递到此方法中(或添加其他值,这非常简单),其他所有内容都将被视为 false

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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文