[英]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.