简体   繁体   中英

Javascript - Nice way to convert 1/0 & 'true'/'false' & true/false to boolean

I have a variable that could sometimes be passed as 1/0 (both integer number or the string number), or it could be passed as a string 'true'/'false' or as an actual boolean true/false. I want to convert all of the cases to an actual boolean.

Other than doing a bunch of if statements and the === is there a faster and more elegant way of doing this?

Use an object with the mappings:

var translations = {
    "true": true,
    "1": true,
    "false": false,
    "0": false
};

And then

var my_value = "true";  # or 1, "false", 0... etc
var my_bool = translations[my_value];

In JS the keys of an object are automatically converted to string (by calling .toString if my memory does not fail), therefore true and "true" will return the same results. Same thing with 0 and "0"

EDIT

If your environment supports it, it would be even better to use a completely empty object:

var translations = Object.create(null);
translations['true'] = true;
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM