简体   繁体   English

Javascript +运算符vs-运算符

[英]Javascript + operator vs - operator

I am puzzled by this snippet : 这个片段让我感到困惑:

var n1 = 5-"4";
var n2 = 5+"4";

alert(n1);
alert(n2);

​I understand that n1 is 1. That is because a minus operator would convert the string "4" into number and subtract it from 5. But why do we get 54 in case of + operator? ``我知道n1是1.这是因为减号运算符会将字符串“ 4”转换为数字并从5中减去。但是为什么在+运算符的情况下得到54?

Can someone explain this difference between + and = operators to me? 有人可以向我解释+和=运算符之间的区别吗?

By type conversion any + expression, that contains a strings, will result in a string. 通过类型转换,包含字符串的任何+表达式都会产生一个字符串。 Thus all operands (in your case 5 ) will be converted to a string, before executing the concatenation. 因此,在执行串联之前,所有操作数(在您的情况下为5 )都将转换为字符串。

- on the other hand is just an arithmetic operand, thus "4" is converted to an integer and the calculation is performed as you expect. -另一方面,它只是一个算术操作数,因此将"4"转换为整数,然后按预期执行计算。

It's because in n2 , + is being treated as concatenation, not addition. 这是因为在n2+被视为串联,而不是加法。 So 5 is converted to the string "5" and "4" is concatenated, giving "54". 因此将5转换为字符串"5"并连接"4" ,得到“ 54”。

When there's a string in either side of + , the + will be considered as a string concatenating operator, the other side will be converted to string and then do the concatenating. +任一侧都有字符串时, +将被视为字符串连接运算符,另一侧将转换为字符串,然后进行连接。

And be careful of something like 1+2+'3' , the result is '33' rather than '123' . 并注意1+2+'3'之类的结果,结果为'33'而不是'123'

- operator has only one meaning - numbers subtraction (or negation and in that case, also conversion to number). -运算符只有一个含义-数字减法(或取反,在这种情况下,还转换为数字)。 In case of + operator, however, there are two: number addition and strings concatenation. 但是,在+运算符的情况下,有两个:数字加法字符串串联。 When one of the operands of + operator is a string it does string concatenation instead of numbers addition. +运算符的操作数之一是字符串时,它将进行字符串连接而不是数字加法。

The entire process is a bit more complicated than that though and involves an algorithm that you can learn a bit more here , for example. 整个过程比这要复杂一些,例如,涉及一种可以在此处学到更多知识的算法。

The + operator is also a string operator. +运算符也是字符串运算符。 Quite every basic type variable in javascript can be interpreted also in its string representation. javascript中的每个基本类型变量都可以用其字符串表示形式进行解释。 You are just attaching 5 to 4 getting 54. 您只需将5附加到4即可获得54。

The - operator is not a string operator so the compiler tries to interpret "4" as a number, thus getting 1 -运算符不是字符串运算符,因此编译器尝试将“ 4”解释为数字,从而得到1

Javascript takes 5 as a number and "4" as string. Javascript以5作为数字,以“ 4”作为字符串。 The javascript + operator use to concat two things. javascript +运算符用于连接两件事。 If you want to addition please use parseInt. 如果要添加,请使用parseInt。

var n1 = 5-"4";
var n2 = parseInt(5)+parseInt("4");

alert(n1);
alert(n2);

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

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