简体   繁体   English

JavaScript中的'2'+'2' - '2'= 20怎么样?

[英]How is '2'+'2'-'2'= 20 in JavaScript?

I was just randomly playing around JavaScript. 我只是随机玩JavaScript。 The '2'+'2'-'2' input I given to it. 我给它的'2'+'2'-'2'输入。

and the output is surprisingly 20 . 令人惊讶的是输出20

 console.log('2'+'2'-'2'); 

Now I am not getting it. 现在我没有得到它。

Does anyone explain is to me Why it is like this? 有人向我解释为什么会这样? How can be output of this equal to 20 ? 怎么可以输出这个等于20

+ is both concatenation and addition. +是连接和添加。 If any of the arguments are not numeric, then it's concatenation. 如果任何参数不是数字,那么它就是连接。 Thus, '2' + '2' is '22' - just like "foo" + "bar" are "foobar" , and just like 3 + {} is "3[object Object]" . 因此, '2' + '2''22' - 就像"foo" + "bar""foobar" ,就像3 + {}"3[object Object]"

- is only subtraction. -只是减法。 No matter what its arguments are, they are coerced to numbers. 无论它的论点是什么,它们都被强迫数字。 Thus, '22' - '2' is evaluated as 22 - 2 , which is 20. 因此, '22' - '2'被评估为22 - 2 ,即20。

JavaScript performs string concatenation when find + . 当find +时,JavaScript执行字符串连接。 So the first "2" and second "2" makes "22". 所以第一个“2”和第二个“2”变为“22”。

But when performing subtraction ( - ) on strings, coercion happens. 但是当对字符串执行减法( - )时,会发生强制 So the resulted "22" coerced to number 22 and final "2" coerced to number 2 . 因此结果“22” 被迫22 ,最后“2” 被强制2 Finally subtracts 2 from 22 to result 20 . 最后从22减去2到结果20

For More: Coercion 更多: 强制

Step by step evaluation: 分步评估:

'2' + '2' - '2' To '2' + '2' - '2'

'22' - '2' To '22' - '2'

22 - 2 To 20 22 - 220

The mechanism at play in JavaScript is called coercion . JavaScript中使用的机制称为coercion

The + sign in JavaScript can either perform string concatenation, or arithmetic addition. JavaScript中的+符号可以执行字符串连接或算术添加。 So how does JavaScript choose which action to perform? 那么JavaScript如何选择要执行的操作?

In case both arguments (on either side of the +) are strings, JavaScript performs a concatenation. 如果两个参数(在+的两侧)都是字符串,JavaScript会执行连接。

 console.log(2 + 2); // 4 console.log('2' + '2'); // '22' 

The minus sign however has only one meaning: the arithmetic subtraction. 然而,减号只有一个含义:算术减法。

So JavaScript has only one way to interpret '22' - 2 which is to subtract 2 from '22'. 所以JavaScript只有一种方法来解释'22' - 2 ,即从'22'中减去2。 But of course '22' is not a number, so JavaScript first forces it ("coerces" it) into a number. 但当然'22'不是一个数字,所以JavaScript首先强迫它(“强制”它)成一个数字。

The real operation performed is 22 - 2 , which easily computes to 20 , the result you observe. 执行的实际操作是22 - 2 ,很容易计算到20 ,您观察到的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM