var x = 5;
如果我运行 console.log('The number is ' + x);
输出为数字为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's Docs 中查看更多信息
关于javascript - JavaScript 类型强制如何以及为何起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62097773/