Home > Article > Web Front-end > Interpret JavaScript code var ie = !-[1,]
var ie = !-[1,];
This code was called the shortest IE judgment code in the world before IE9. Although the code is short, it does contain a lot of basic JavaScript knowledge. In this example, when the code is executed, the toString() method of the array will be called first. When [1,].toString() is executed, "1," will be obtained in IE6, 7, and 8. Then the expression becomes !-"1,". Then try to convert "1," into a numeric type to get NaN, and then negative NaN to get the value still NaN. Finally execute !NaN and return true. Let’s review the javascript knowledge involved in the code by decomposing this statement:
Differences in browser array literal parsing
[1,] means that an array is defined using javascript’s array literal. In IE6, 7, and 8, the array has two elements, and the values in the array are 1 and undefined respectively. In standard browsers, undefined after the first element is ignored, and the array contains only one element, 1.
The toString() method of the array
When calling the toString() method of the array object, the toString() method will be called for each element in the array. If the value of the element is NULL or undefined, an empty string will be returned. Then the obtained values of each item are assembled into a string separated by commas ",".
Unary minus operator
When using the unary minus operator, if the operand is a numeric type, the operand will be negatived directly. Otherwise, it will first try to convert the operand to a numeric type. The conversion process is equivalent to executing the Number function. Then take the negative of the result.
Logical NOT operation
When performing logical NOT operation, it returns true if the operand is NaN, NULL or undefined.
With the above knowledge, we can derive the code var ie = !-[1,]; which is actually equivalent to var ie = !(-Number([1,].toString())); The value is true in IE678.