Convert string to Boolean in javascript

This question already has an answer here:

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

  • 我会在这里使用一个简单的字符串比较,据我所知,没有内置函数用于你想要做的事情(除非你想诉诸eval ...你不这样做)。

    var myBool = myString == "true";
    

    I would like to answer this to improve upon the accepted answer.

    To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.

    function stringToBool(val) {
        return (val + '').toLowerCase() === 'true';
    }
    

    JSPerf

    在这里输入图像描述


    you can also use JSON.parse() function

    JSON.parse("true") returns true (Boolean)

    JSON.parse("false") return false (Boolean)

    链接地址: http://www.djcxy.com/p/75068.html

    上一篇: 在JavaScript中投射一个布尔

    下一篇: 在javascript中将字符串转换为布尔值