Javascript - Nice way to convert 1/0 & 'true'/'false' & true/false to boolean -
Javascript - Nice way to convert 1/0 & 'true'/'false' & true/false to boolean -
i have variable passed 1/0 (both integer number or string number), or passed string 'true'/'false' or actual boolean true/false. want convert of cases actual boolean.
other doing bunch of if statements , === there faster , more elegant way of doing this?
use object 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 keys of object automatically converted string (by calling .tostring if memory not fail), hence true , "true" homecoming same results. same thing 0 , "0"
edit
if environment supports it, improve utilize empty object:
var translations = object.create(null); translations['true'] = true; ... javascript
Comments
Post a Comment