What is the most reliable way to pass a boolean to a jQuery plugin?

When creating a jQuery plugin that needs to be passed a boolean, what is the most reliable way to convert input to a boolean in a user-friendly way?

To be more precise: I am afraid that people may pass a string 'false'(instead of a simple one false), and therefore a simple conversion will !!optioneither Boolean(option)return a “wrong” value ( !!'false'- true).

I am currently checking my var optionas follows:

if (typeof(option) != 'boolean'){
    if (option === 'false'){
        option = false; //fake false
    } else {
        option = !!option; //everything else is converted as truthy / falsy in a standard manner  
    }
}

but I was wondering if there is a more elegant and concise way to do this, or is this exactly how JavaScript handles this?

+3
source share
3

, , -

if (typeof(option) != 'boolean')
    console.error('Function X expects a Boolean.');

, , 0 1. no yes?

; .


JS /, . ?

+4

.

var result = ( userInput === true );

true - , true. . , .

... , .

var getBooleanValue = function( userInput ){
    if( !userInput ){
        return false;
    }
    var boolNames = {
        'true':1, 'yes':1,
        'false':0,'no':0,
        'yourMoM':1
    };
    return (userInput in boolNames && !!boolNames[ userInput ])|| ( userInput === true );
};
var tests = [
    [ true, true ],
    [ 'true', true ],
    [ 'yes', true ],

    [ false, false ],
    [ 'false', false ],
    [ 'no', false ]
];
var runTest = function( tests ){
    var i = tests.length;
    while( i-- ){
        if( getBooleanValue(tests[i][0]) !== tests[i][1] ){
            throw new Error( "Test error: getBooleanValues( " + tests[i][0] + ") should return " + tests[i][1] );
        }
    }
};
runTest( tests );
+4

- :

var falsey = ["0", "", "false", "null", "undefined", "NaN"];
var isFalse = false;

for(var i = 0, len = falsey.length; i < len; i++){
    if(options + "" == falsey[i]){
        isFalse = true;
        break;
    }
}

, , , options falsey 0, "", false, null, undefined, NaN

This will detect them no matter what they were (the technique is similar to the upper case of both search words and comparison words)

Since the list is short, you can also do this using switch cases, otherwise ifs

+3
source

All Articles