Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

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

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

funescape = function( _, escaped ) {
    var high = "0x" + escaped - 0x10000;
    // NaN means non-codepoint
    return high !== high ?            // <--- LINE 129
        escaped :
        // BMP codepoint
        high < 0 ?
            String.fromCharCode( high + 0x10000 ) :
            // Supplemental Plane codepoint (surrogate pair)
            String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};

What is the reason to make high !== high comparison? It looks like return escaped will never be executed. Or do I miss something?

Reference: jQuery Sizzle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...