【发布时间】:2014-07-30 09:37:21
【问题描述】:
为什么在 JavaScript 中我可以使用数字字符串执行诸如乘法和减法之类的运算。 “10”带数字?
JavaScript 是否进行类型推断?
考虑下面的例子,为什么在最后两个语句中我得到 1010 而不是 20?
var foo = "Hello, world!";
var bar = "10";
var x = foo * 10; // x is now bound to type number
console.log("type of x= " + typeof x + ", value of x= " + x); // this will print number NaN, that makes sense..
var y = bar * 10; // y is now bound to type number
console.log("type of y= " + typeof y + ", value of y= " + y); // this will print number 100
y = bar - 10; // y is now bound to type number
console.log("type of y= " + typeof y + ", value of y= " + y); // this will print number 0
y = bar + 10; // y is now bound to type string!!
console.log("type of y= " + typeof y + ", value of y= " + y); // this will print number 1010
y = eval(bar + 10); // y is now bound to type number!!!!
console.log("type of y= " + typeof y + ", value of y= " + y); // this will print number 1010
日志输出:
type of x= number, value of x= NaN
type of y= number, value of y= 100
type of y= number, value of y= 0
type of y= string, value of y= 1010
type of y= number, value of y= 1010
【问题讨论】:
-
加号既用于字符串连接,也用于添加数字,因此当其中一个值是字符串时,另一个值也被合并为字符串。您不能对字符串进行乘法运算或减法运算,因此当使用这些运算符时,这些值会与数字相一致。
-
在这里找到好的解决方案:stackoverflow.com/questions/7124884/…
标签: javascript types type-conversion