[英]How can I cast a variable to the type of another in 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
}
so that convertToType(1, "15") returns 15, convertToType("1", 15) returns "15", convertToType(false, "True") returns true, etc. 因此convertToType(1,“ 15”)返回15,convertToType(“ 1”,15)返回“ 15”,convertToType(false,“ True”)返回true,依此类推。
To reiterate, I want to be able to dynamically cast variables to the types of other variables. 重申一下,我希望能够将变量动态地转换为其他变量的类型。
Is this possible? 这可能吗?
UPDATE: here's an even more complete example, with tests (requires Node 6+ or some transpilation to ES5): https://github.com/JaKXz/type-convert 更新:这是一个甚至更完整的示例,带有测试(需要Node 6+或向ES5的一些移植): https : //github.com/JaKXz/type-convert
You can use the typeof
operator to get the right "casting" function: 您可以使用typeof
运算符获取正确的“广播”功能:
function convertToTypeOf(typedVar, input) {
return {
'string': String.bind(null, input),
'number': Number.bind(null, input)
//etc
}[typeof typedVar]();
}
Try it out here: http://jsbin.com/kasomufucu/edit?js,console 在这里尝试: http : //jsbin.com/kasomufucu/edit?js,console
I would also suggest looking into TypeScript for your project. 我也建议您为您的项目研究TypeScript 。
It follows my version of JaKXz answer that is supposedly more efficient by switching on inferred type. 它遵循了我的JaKXz回答版本,据说可以通过打开推断类型来提高效率。 In the case of number
and boolean
the conversion is loose: in case of invalid input it will output NaN
and false
, respectively. 对于number
和boolean
,转换是宽松的:如果输入无效,它将分别输出NaN
和false
。 You can work on this by adding your stricter validation and more types. 您可以通过添加更严格的验证和更多类型来进行处理。
function convertToTypeOf(typevar, input)
{
let type = typeof typevar;
switch(type)
{
case "string":
return String.bind(null, input)();
case "number":
return Number.bind(null, input)();
case "boolean":
return input == "true" ? true : false;
default:
throw "Unsupported type";
}
}
console.log(convertToTypeOf("string", 1)); // Returns "1"
console.log(convertToTypeOf("string", true)); // Returns "true"
console.log(convertToTypeOf("string", false)); // Returns "false"
console.log(convertToTypeOf(1.2, "1")); // Returns 1
console.log(convertToTypeOf(1.2, "1.5")); // Returns 1.5
console.log(convertToTypeOf(true, "false")); // Returns false
console.log(convertToTypeOf(false, "true")); // Returns true
console.log(convertToTypeOf(1, "asd")); // Returns NaN
console.log(convertToTypeOf(true, "asd")); // Returns false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.