Declaring a boolean in JavaScript using just var

后端 未结 8 1544
余生分开走
余生分开走 2020-12-23 02:54

If I declare a JavaScript boolean variable like this:

var IsLoggedIn;

And then initialize it with either true or 1

相关标签:
8条回答
  • 2020-12-23 03:30

    If you want IsLoggedIn to be treated as a boolean you should initialize as follows:

    var IsLoggedIn=true;
    

    If you initialize it with var IsLoggedIn=1; then it will be treated as an integer.

    However at any time the variable IsLoggedIn could refer to a different data type:

     IsLoggedIn="Hello World";
    

    This will not cause an error.

    0 讨论(0)
  • 2020-12-23 03:30

    How about something like this:

    var MyNamespace = {
        convertToBoolean: function (value) {
            //VALIDATE INPUT
            if (typeof value === 'undefined' || value === null) return false;
    
            //DETERMINE BOOLEAN VALUE FROM STRING
            if (typeof value === 'string') {
                switch (value.toLowerCase()) {
                    case 'true':
                    case 'yes':
                    case '1':
                        return true;
                    case 'false':
                    case 'no':
                    case '0':
                        return false;
                }
            }
    
            //RETURN DEFAULT HANDLER
            return Boolean(value);
        }
    };
    

    Then you can use it like this:

    MyNamespace.convertToBoolean('true') //true
    MyNamespace.convertToBoolean('no') //false
    MyNamespace.convertToBoolean('1') //true
    MyNamespace.convertToBoolean(0) //false
    

    I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

    0 讨论(0)
提交回复
热议问题