Convert truthy or falsy to an explicit boolean

后端 未结 2 648
天涯浪人
天涯浪人 2020-12-02 18:18

I have a variable. Let\'s call it toto.

This toto can be set to undefined, null, a string, or an object.

相关标签:
2条回答
  • 2020-12-02 18:22

    Yes, you can always use this:

    var tata = Boolean(toto);
    

    And here are some tests:

    for (var value of [0, 1, -1, "0", "1", "cat", true, false, undefined, null]) {
        console.log(`Boolean(${typeof value} ${value}) is ${Boolean(value)}`);
    }
    

    Results:

    Boolean(number 0) is false
    Boolean(number 1) is true
    Boolean(number -1) is true
    Boolean(string 0) is true
    Boolean(string 1) is true
    Boolean(string cat) is true
    Boolean(boolean true) is true
    Boolean(boolean false) is false
    Boolean(undefined undefined) is false
    Boolean(object null) is false
    
    0 讨论(0)
  • 2020-12-02 18:22

    You can use Boolean(obj) or !!obj for converting truthy/falsy to true/false.

    var obj = {a: 1}
    var to_bool_way1 = Boolean(obj) // true
    var to_bool_way2 = !!obj // true
    
    0 讨论(0)
提交回复
热议问题