如何在 Javascript 中将变量转换为另一个变量的类型
问题描述:
我希望能够将一个变量转换为另一个变量的特定类型.举个例子:
I want to be able to cast a variable to the specific type of another. As an example:
function convertToType(typevar, var) {
return (type typevar)var; // I know this doesn't work
}
这样 convertToType(1, "15") 返回 15,convertToType("1", 15) 返回 "15",convertToType(false, "True") 返回 true,等等
so that convertToType(1, "15") returns 15, convertToType("1", 15) returns "15", convertToType(false, "True") returns true, etc.
重申一下,我希望能够将变量动态转换为其他变量的类型.
To reiterate, I want to be able to dynamically cast variables to the types of other variables.
这可能吗?
答
function convertToType (t, e) {
return (t.constructor) (e);
}
注意当我们想将 15 转换为数字时的第一次调用,我们在第一个参数后附加了一个点 (.)
note the first call when we wanted to convert 15 to a Number, we append a dot (.) to the first parameter