Cleanest way to convert to boolean

This question already has an answer here:

  • How can I convert a string to boolean in JavaScript? 71 answers

  • 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
    
    链接地址: http://www.djcxy.com/p/75072.html

    上一篇: 使用javascript从字符串中删除双引号

    下一篇: 最干净的方式来转换为布尔值