Strange code in jQuery sources: var !== var ? x : y;

前端 未结 3 1455
清酒与你
清酒与你 2020-12-08 00:31

Recently I found one weird line in the jQuery sources (last version 1.9.1, Sizzle package, line 129 funescape function):

funescape = function( _         


        
3条回答
  •  不思量自难忘°
    2020-12-08 00:57

    In fact it is written in the comment right above:

    // NaN means non-codepoint

    So it is mandatory to perform this comparison first to handle the NaN case as in JavaScript:

    NaN === NaN returns false.

    As pointed out by James Wiseman it is also important to know why the developer used high !== high instead of isNaN(high) which would have been clearer.

    It is certainly based on performance. This test shows that a !== a is twenty times faster than isNaN(a).

    zzzzBov also indicates that isNaN() could be overwritten, using !== is also more portable.

    More info from Benjamin Gruenbaum:

    It is also worth noting that NaN does not equal to anything else as well, and also it is not equal to anything else in an unstrict sense

    And from Jan Dvorak:

    Also note {valueOf:function(){return{}}} does equal itself

提交回复
热议问题