[英]Clarification required in Javascript coercion example
var a = 1+1+'2';
console.log(a);
> 22
var a = 1+1+'2'+7;
console.log(a);
> 227
var a = 1+1+'2'+7+10;
console.log(a);
> 22710
var a = 1+1+'2'+7+10-2;
console.log(a);
> 22708
where is the 0 coming from in 22708? 0在哪里来自22708? coercion example. 强制的例子。
The hint is in the previous evaluation. 提示在先前的评估中。 1+1+'2'+7+10-2
is equivalent to ((1+1)+'2'+7+10)-2
, or "22710"-2
. 1+1+'2'+7+10-2
相当于((1+1)+'2'+7+10)-2
或"22710"-2
。 While +
is defined for both strings and numbers (it's addition when both arguments are numbers, concatenation in any other case), -
is only defined for numbers; 虽然为字符串和数字都定义了+
(当两个参数都是数字时是加号,在任何其他情况下都是串联的), -
仅为数字定义了; and so "22710"
is coerced to number: 22710-2
is indeed 22708
. 因此"22710"
被强制为数字: 22710-2
的确是22708
。
Javascript handles the subtract and minus signs differently. JavaScript处理减号和减号的方式不同。 You get the zero because it is taking 22710
and subtracting 2 to get 22708
. 您得到零,因为它用22710
减去2得到22708
。
So it goes from 2
To 22
To 227
To 22710
To 22710 - 2
Which gives 22708
所以它从2
到22
到227
到22710
到22710 - 2
得出22708
The actual reason as to why is way over my head though. 至于为什么的实际原因却远远超过了我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.