Is there a generic way to explicitly cast a variable to a specific type? For example:
var b = true;
var str = "";
var n = 5;
cast(someVariable, typeof b); //someVariable become a boolean
cast(someVariable, typeof str); //someVariable become a string
cast(someVariable, typeof n); //someVariable become an integer
where a cast
is supposed to be that magic casting method.
That's obvious that I can just enumerate in a switch
all possible types. But is there a [beautiful] native way to do that?
You can do it using mapping:
var castMap = {
"boolean" : Boolean
};
var b = true;
var someVariable = "true";
castMap[typeof(b)](someVariable)
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.