为什么在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
第二个例子
var y = bar * 10
Javascript假设你想要执行一个数学运算,并将你的原始字符串强制转换成一个数字。
在最后两个示例中,您试图将10(数字)添加到bar中。bar(你的变量)是一个字符串,所以JavaScript尽其所能,假设你想要一个字符串作为结果,并通过连接"10"(作为一个字符串)创建一个字符串,而不是将你的原始字符串强制为一个数字。
类型强制转换的规则很复杂。我帮你找找链接。但是Douglas Crockford的《JavaScript: The Good Parts》是一本很好的书。
编辑试试这个,解释得很好。
http://united-coders.com/matthias-reuter/all-about-types-part-2/