简体   繁体   English

为什么'+'运算符在JavaScript中的行为不同于'*','/'和'-'运算符

[英]Why does the '+' operator behave different from '*' ,'/' and '-' operator in javascript

When we perform sum operation between two elements, it needs to be converted into a number, without converting it merges them because element.val() returns a string. 当我们在两个元素之间执行求和运算时,需要将其转换为数字,而无需转换即可合并它们,因为element.val()返回一个字符串。 But when we perform other operations like multiply, subtraction or divide it gives the expected result without performing any typecast. 但是,当我们执行其他运算(例如乘法,减法或除法)时,它会得到预期的结果,而无需执行任何类型转换。

 function add() { alert($("#first").val() + $("#second").val()); } function divide() { alert($("#first").val() / $("#second").val()); } function multi() { alert($("#first").val() * $("#second").val()); } function subst() { alert($("#first").val() - $("#second").val()); } 
 <input type="text" Id="first" /> <input type="text" Id="second" /> <input type="button" Id="add" onclick="add()" value="+"/> <input type="button" Id="divide" onclick="divide()" value="/"/> <input type="button" Id="multi" onclick="multi()" value="*" /> <input type="button" Id="subst" onclick="subst()" value="-"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

+ operator is used either for concatenating strings or for adding numbers (the interpretter will favor the concatenation if one of the operands is a string). +运算符用于连接字符串或添加数字(如果操作数之一是字符串,则解释器将倾向于连接)。 But / , * and % are used only with numbers so the interpretter is forced to see the operands as numbers. 但是/*%仅与数字一起使用,因此强制解释器将操作数视为数字。

For more explanation, here is an answer I gave about two days ago for a similar question. 有关详细的解释,这里是一个答案我给大约两天前的一个类似的问题。 (It's pretty long so I won't repost it here again). (很长,所以我不再在这里重新发布)。

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

相关问题 为什么JavaScript“delete”运算符在不同的浏览器中表现不同? - Why does the JavaScript “delete” operator behave differently in different browsers? 为什么&#39;&lt;&lt;&#39;运算符在Javascript和PHP中的行为有时会有所不同? - Why does the '<<' operator sometimes behave differently in Javascript and PHP? 为什么 || JavaScript 中的 (or) 和 &amp;&amp; (and) 运算符的行为与 C 中的不同(返回非布尔值)? - Why does the || (or) and && (and) operator in JavaScript behave differently than in C (returning non boolean value)? 为什么|| 操作员不能在 JavaScript 中工作? - Why does the || operator not work in JavaScript? 为什么 switch case 中的逻辑 OR 运算符会表现得很奇怪? - Why does the logical OR operator in switch cases behave strangely? Javascript:为什么前缀运算符只能与模数一起使用,而不能与后缀运算符一起使用? - Javascript: Why does prefix operator work with modulus but not postfix operator? javascript中的XOR运算符与python中的XOR运算符不同 - XOR operator in javascript different from XOR operator in python Javascript:为什么 % 运算符作用于字符串? - Javascript : Why does % operator work on strings? JavaScript是否支持&lt;=运算符? - Does JavaScript support <= operator? 在Javascript中,为什么“this”运算符不一致? - In Javascript, why is the “this” operator inconsistent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM