Home > Web Front-end > JS Tutorial > Interpret JavaScript code var ie = !-[1,] The shortest IE judgment code_javascript skills

Interpret JavaScript code var ie = !-[1,] The shortest IE judgment code_javascript skills

WBOY
Release: 2016-05-16 18:06:21
Original
1009 people have browsed it

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 exampleWhen the code is executed, it will first call the toString() method of the array , and execute [1,].toString() In IE6,7,8 you will get "1,". Then the expression becomes !-“1,”. Try converting "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 array literal parsing between browsers

[1,] means that an array is defined using the array literal of JavaScript. 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.

toString() method of 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, and then each obtained The value of the item is spelled 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, and then taking the negative result.

Logical NOT operation

Returns true if the operand is NaN, NULL or undefined when performing a logical NOT operation.

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. If there is anything wrong with the analysis or if you have any different opinions, please correct me!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template