【发布时间】:2020-09-17 17:17:30
【问题描述】:
var x = 5;
如果我运行console.log('The number is ' + x);
输出为The number is 5;
但我的问题是为什么数字转换成字符串?
【问题讨论】:
标签: javascript string types type-coercion
var x = 5;
如果我运行console.log('The number is ' + x);
输出为The number is 5;
但我的问题是为什么数字转换成字符串?
【问题讨论】:
标签: javascript string types type-coercion
在类型强制中,即比较或计算不同类型的两个操作数,其中一个将转换为等效类型。 number 转换为 string 的原因是因为每个数字都可以是字符串但反之并不总是如此,所以类型强制总是将数字转换为字符串
【讨论】:
这只是因为你在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.