Concatenation vs. Addition with the ( ) Operator in Javascript
When using the ' ' operator in Javascript, it's important to be aware of its dual nature, as it can be used for both concatenation and addition. This can lead to unexpected results, such as when trying to add numbers and instead getting a concatenated string.
Consider the following code:
<p>i = 1</p> <p>divID = "question-" + i+1;</p>
This code would result in 'question-11' being assigned to 'divID', rather than the expected 'question-2'. This is because Javascript evaluates the expression from left to right, and 'i' is first concatenated to the string 'question-'.
To avoid this issue and correctly perform addition, use parenthesis to enforce the order of operations:
<p>divID = "question-" + (i+1);</p>
This forcesJavascript to evaluate the expression 'i 1' first, which results in the addition of 'i' and '1', giving us '2'. Then, this value is concatenated to the string 'question-', resulting in the correct output 'question-2'.
Remember that the ' ' operator can perform both concatenation and addition, and the order of operations can impact the result. Use parentheses to explicitly define the order of operations when combining numeric and string values.
The above is the detailed content of Why Does \'1 1\' Sometimes Equal \'11\' in Javascript?. For more information, please follow other related articles on the PHP Chinese website!