Javascript 为什么我可以将一个字符串和一个数字相乘和相减
为什么在JavaScript中,我可以对数字字符串执行乘法和减法等操作,例如数字“10” JavaScript做类型推断吗 考虑下面的例子,为什么在最后两个语句中我得到1010而不是20Javascript 为什么我可以将一个字符串和一个数字相乘和相减,javascript,types,type-conversion,Javascript,Types,Type Conversion,为什么在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= " +
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(您的变量)是一个字符串,因此JavaScript会尽最大努力,假设您想要一个字符串作为结果,并通过连接“10”(作为字符串)创建一个字符串,而不会强制将原始字符串设置为数字
类型强制的规则很复杂。我会尽力为你找到一个链接。但是道格拉斯·克罗克福德的《JavaScript:好的部分》是一本好书
编辑
试试这个,很好地解释了这一切
加号用于字符串连接和数字相加,因此当其中一个值是字符串时,另一个值也会被关联到字符串中。您不能对字符串进行乘法或减法运算,因此当使用这些运算符时,值会与数字相关联。这里有一个很好的解决方案: