繁体   English   中英

JavaScript 类型强制如何以及为何起作用?

[英]How and why JavaScript type coercion works?

var x = 5;

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

output The number is 5;

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

这只是因为您在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 的文档中查看更多信息

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM