var x = 5;
如果我运行console.log('The number is ' + x);
输出结果为The number is 5;
但是我的问题是,为什么数字会被转换成字符串呢?
var x = 5;
如果我运行console.log('The number is ' + x);
输出结果为The number is 5;
但是我的问题是,为什么数字会被转换成字符串呢?
console.log
命令中写的内容输出了一个字符串,因此当你使用'The number is ' + x
时,实际上你做的是将字符串连接起来。console.log(x)
,你会得到一个整数响应。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));
number
转换为string
的原因是因为每个数字都可以是字符串,但相反并非总是如此,因此类型强制转换始终将数字转换为字符串。
Number
添加到String
中,则默认操作是在没有参数的情况下调用Number
上的toString
。默认参数为10
(即基数为10),这将将其转换为字符串文字“5”,然后将其连接到“The number is”中。最后,console.log
获取此参数并对其调用util.inspect
,并且对于字符串参数的此调用的输出是以其字符串形式打印输入参数到process.std.out
,并附加行结束符。示例实现:https://console.spec.whatwg.org/#nodejs-printer-example。 - Supernovah