A single plus sign has three functions as an operator in JavaScript. It can represent string concatenation, for example:
or a unary operator that represents a positive value of a number, for example:
or represents the summation operation of numerical expressions, for example:
Among the three representations, string concatenation and numerical summation are prone to ambiguity. Because the processing of these two operations in JavaScript will depend on the data type, it cannot be judged from the operator. Let’s look at an expression alone:
The main problem raised by the plus sign " " relates to another rule. This rule is "If there are strings in the expression, string concatenation is preferred." For example:
We see that the IMG element with the id testPic has a border with a width of 1 - the default unit px (pixel, pixel point) is omitted. But if you try to widen its borders with the following code, it will cause an error (some browsers ignore the value, others will pop up exceptions, and some browsers may crash):
Because in fact in the DOM model, borderWidth is a united string value, so the value here will be "1px". JavaScript itself does not make errors, it will complete operations similar to the following and assign the value to borderWidth:
At this time, the browser's DOM model cannot interpret the meaning of "1px10", so an error occurs. When you read the borderWidth value again, it will still be the value 1px. So, how to prove the above operation process? The following code will show that the result of the JavaScript operation is 1px10, but when assigned to borderWidth, the DOM ignores this wrong value, so borderWidth is not actually modified:
Later, W3C promoted the XHTML specification and tried to avoid this problem from the first aspect, but the impact on the development community was still limited. Therefore, in the manuals provided by browser developers, the data type of each attribute will be stated as much as possible to prevent developers from writing code like the above. In this case, the most correct way to write it is: