【问题标题】:How and why JavaScript type coercion works?JavaScript 类型强制如何以及为什么起作用?
【发布时间】:2020-09-17 17:17:30
【问题描述】:

var x = 5;

如果我运行console.log('The number is ' + x);

输出为The number is 5;

但我的问题是为什么数字转换成字符串?

【问题讨论】:

    标签: javascript string types type-coercion


    【解决方案1】:

    在类型强制中,即比较或计算不同类型的两个操作数,其中一个将转换为等效类型。 number 转换为 string 的原因是因为每个数字都可以是字符串但反之并不总是如此,所以类型强制总是将数字转换为字符串

    【讨论】:

      【解决方案2】:

      这只是因为你在console.log 命令中写的输出了一个字符串,所以当你使用'The number is ' + x 时你所做的本质上是字符串连接。

      另一方面,如果你使用console.log(x),你会得到一个 int 响应。

      您可以在这里查看:

      var x = 5;
      
      console.log("The number is " + x);
      console.log(typeof ("The number is " + x));
      
      console.log(x);
      console.log(typeof x);
      
      console.log(x + x);
      console.log(typeof (x + x));

      您可以在MDN's Docs查看更多信息

      【讨论】:

      • 如果您尝试将Number 添加到String,默认操作是在不带参数的Number 上调用toString。默认参数是10(即基数为10),这会将其转换为字符串文字"5",然后将其连接到"The number is "。最后,console.log 接受此参数并在其上调用util.inspect,此调用对字符串参数的输出是以字符串形式将输入参数打印到process.std.out,并在其末尾附加一行。一个示例实现:console.spec.whatwg.org/#nodejs-printer-example.
      猜你喜欢
      • 2012-12-30
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2013-03-17
      • 2019-09-30
      • 2012-09-28
      • 2014-11-15
      相关资源
      最近更新 更多