简体   繁体   English

如何在Javascript中将变量强制转换为另一个变量的类型

[英]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

function convertToType (t, e) {
    return (t.constructor) (e);
}

复制演示

note the first call when we wanted to convert 15 to a Number, we append a dot (.) to the first parameter 当我们想将15转换为数字时,请注意第一个调用,我们在第一个参数后附加一个点(。)

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. 对于numberboolean ,转换是宽松的:如果输入无效,它将分别输出NaNfalse 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.

相关问题 如何在 JavaScript 中将普通 object 转换为另一种类型的实例 - How to cast a plain object as a instance of another type in JavaScript 如何在javascript中的另一个<script>中使用一个<script>的变量? - How can I use a variable of one <script> in another <script> in javascript? 如何从另一个 JavaScript 文件导入变量? - How can I import a variable from another JavaScript file? 如何在 javascript 的另一个 function 中使用 function 的变量? - how can i use a variable of a function in another function in javascript? 如何使用 javascript 检查变量是否为特定类型? - How can I check if a variable is a specific type using javascript? 如何将自定义类型转换为原始类型? - How can I cast custom type to primitive type? 如何用另一个变量定义变量? - How can I define a variable with another variable? Javascript:可以将字符串强制转换为类型常量/将其转换为类型常量吗? - Javascript: Can a string be cast as/converted to a type constant? 如何在HTML iFrame中将Javascript变量设置为来自父级的另一个变量的值? - How can I set a Javascript variable in an HTML iFrame to the value of another variable from the parent? JavaScript:如何分配与同一对象内的另一个变量相同的变量? - JavaScript: How can I assign a variable the same as another variable inside the same object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM