When I wrote JS a few days ago and tracked and debugged it, I found that the parameter type was mistakenly passed. [what was originally required was the number type, but the real parameter passed in the result was the string type ]. As a result, no exceptions were generated and the execution was still successful.
So today we have made several tests.
(1) Auto-increment of string-type numbers
/* <Br/> * test the auto-increment operation of string-type numbers <br/> */<br/> function teststringselfadd () {<br/> var I = "0"; <br/> for (var j = 0; j <100; j ++) {<br/> I ++; <br/>}< br/> alert ("I =" + I + "" + "I type:" + (typeof I); <br/>}
Test results:
As you can see here, when you add a number in string format, the variable type is changed to number. The Operation also has the same behavior as the number type variable.
Then let's take a look at whether the character "A" will be treated as 97 (its ASCII value) during the auto-increment operation )?
/* <Br/> * test the auto-increment operation of string-type numbers <br/> */<br/> function teststringselfadd () {<br/> // var I = "0"; <br/> var I = "A"; <br/> for (VAR J = 0; j <100; j ++) {<br/> I ++; <br/>}< br/> alert ("I =" + I + "" + "I type: "+ (typeof I); <br/>}
Test results:
As you can see, variables will still be transformed during auto-increment. However, this is not what we expected here. It is converted to an ASCII value, but to Nan. Description: A non-numeric string cannot be used for this operation.
In fact, it is only the number generated on the ++ operator that can be converted to number for calculation, the I ++ here is not equivalent to I = I + 1 in advanced strong-type languages; because I is originally a string type, the ++ here will be reloaded as a connection string.
Test:
/* <Br/> * test the auto-increment operation of string-type numbers <br/> */<br/> function teststringselfadd () {<br/> var I = "0"; <br/> // var I = "A"; <br/> for (VAR J = 0; j <100; j ++) {<br/> // I ++; <br/> I = I + 1; <br/>}< br/> alert ("I =" + I + "" + "I type:" + (typeof I); <br/>}
Test results:
(2) Test the comparison between a string value and a number value:
/* <Br/> * test string comparison <br/> */<br/> function teststringcompare () {<br/> var I = 4; <br/> alert (I <"5"); // returns true <br/> alert ("4" = 4 ); // returns true <br/> alert ("A" = 4); // returns false <br/> alert (""! = 4); // returns true <br/> alert ("A" <4); // returns false <br/> alert ("A"> 4 ); // return false <br/>}
It can be seen that the value in string format is not different from the value in number type.
Therefore, we hope that you will not rely on these "mechanisms" of the JS operators for the next time you use them ". Or, you must check the type correctly to build a saferCode.