【问题标题】:How can I cast a variable to the type of another in Javascript如何在 Javascript 中将变量转换为另一个变量的类型
【发布时间】:2016-11-27 13:00:19
【问题描述】:

我希望能够将一个变量转换为另一个变量的特定类型。举个例子:

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,等等。

重申一下,我希望能够将变量动态转换为其他变量的类型。

这可能吗?

【问题讨论】:

  • JavaScript 是动态类型的。所以不需要函数转换。

标签: javascript types type-conversion


【解决方案1】:
function convertToType (t, e) {
    return (t.constructor) (e);
}

当我们想将 15 转换为数字时,请注意第一次调用,我们在第一个参数后附加一个点 (.)

【讨论】:

  • 唯一的问题是 convertToType(false, 'false') 也计算为 true。我认为布尔运算符坏了。有没有办法解决这个问题?
  • 要从字符串转换为布尔值 false,您需要传入一个空字符串,如下所示:convertToType (false, '')
  • @OfekGila (false, 'false') 工作正常。它不应该返回 false。
  • @OfekGila 它没有损坏,而是按设计工作。这是 ECMA-262 中的相关部分:7.1.2 ToBoolean ( argument )。具体来说,String:如果参数是空字符串(它的长度为零),返回false;否则返回 true。
【解决方案2】:

更新:这是一个更完整的示例,带有测试(需要 Node 6+ 或一些转译为 ES5):https://github.com/JaKXz/type-convert

您可以使用typeof 运算符来获得正确的“强制转换”功能:

function convertToTypeOf(typedVar, input) {
  return {
    'string': String.bind(null, input),
    'number': Number.bind(null, input)
    //etc
  }[typeof typedVar]();
}

在这里试试:http://jsbin.com/kasomufucu/edit?js,console

我还建议为您的项目查看 TypeScript

【讨论】:

  • 不,typeof 告诉您变量保存的数据类型,它不会在数据类型之间转换。
  • 您是否将理解您的答案所必需的信息放在第三方网站上而不是在答案中?
  • @OfekGila 我做了一个更完整的例子,我将编辑帖子以包含它。 :)
  • @Quentin,很抱歉造成混淆,我试图让我的问题更清楚一些。不过,感谢您的回复,但我很清楚预先存在的铸造功能:)
  • @JaKXz 你让我开心。
【解决方案3】:

它遵循我的 JaKXz 答案版本,据说通过打开推断类型更有效。在numberboolean 的情况下,转换是松散的:如果输入无效,它将分别输出NaNfalse。您可以通过添加更严格的验证和更多类型来解决此问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2011-01-28
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多