在 JavaScript 中投射一个 bool

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4594744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:15:00  来源:igfitidea点击:

Cast a bool in JavaScript

javascript

提问by Patrik

Possible Duplicate:
How can I convert a string to boolean in JavaScript?

可能的重复:
如何在 JavaScript 中将字符串转换为布尔值?

Hi,

你好,

How can I cast a String in Bool ?

如何在 Bool 中投射字符串?

Example: "False" to bool false

示例:“假”布尔

I need this for my JavaScript.

我的 JavaScript 需要这个。

Thank you for help !

谢谢你的帮助 !

采纳答案by El Ronnoco

function castStrToBool(str){
    if (str.toLowerCase()=='false'){
       return false;
    } else if (str.toLowerCase()=='true'){
       return true;
    } else {
       return undefined;
    }
}

...but I think Jon's answer is better!

...但我认为乔恩的回答更好!

回答by Pointy

You can do this:

你可以这样做:

var bool = !!someString;

If you do that, you'll discover that the string constant "False"is in fact boolean true. Why? Because those are the rules in Javascript. Anything that's not undefined, null, the empty string (""), or numeric zero is considered true.

如果这样做,您会发现字符串常量"False"实际上是 boolean true。为什么?因为这些是 Javascript 中的规则。任何不是undefinednull、空字符串 ( "") 或数字零的东西都被视为true

If you want to impose your own rules for strings (a dubious idea, but it's your software), you could write a function with a lookup table to return values:

如果你想对字符串强加你自己的规则(一个可疑的想法,但它是你的软件),你可以编写一个带有查找表的函数来返回值:

function isStringTrue(s) {
  var falses = { "false": true, "False": true };
  return !falses[s];
}

maybe.

或许。

edit— fixed the typo - thanks @Patrick

编辑- 修正了错字 - 谢谢@Patrick

回答by Jon

You can use something like this to provide your own custom "is true" test for strings, while leaving the way other types compare unaffected:

您可以使用这样的东西来为字符串提供您自己的自定义“是否为真”测试,同时不影响其他类型的比较方式:

function isTrue(input) {
    if (typeof input == 'string') {
        return input.toLowerCase() == 'true';
    }

    return !!input;
}

回答by ?ime Vidas

function castBool(str) {
    if (str.toLowerCase() === 'true') {
        return true;
    } else if (str.toLowerCase() === 'false') {
        return false;
    }
    return ERROR;
}

ERRORis whatever you want it to be.

ERROR是任何你想要的。