jQuery源代码中的奇怪代码:var!== var? x:y; [英] Strange code in jQuery sources: var !== var ? x : y;

查看:130
本文介绍了jQuery源代码中的奇怪代码:var!== var? x:y;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在jQuery源代码中发现了一个奇怪的行(最新版本1.9.1,Sizzle包,第129行 funescape 函数):

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 obviously looks like return escaped will never be executed. Or do I miss something?

参考: https://github.com/jquery/sizzle/blob/master/sizzle.js#L129

推荐答案

事实上它写在上面的评论中:

In fact it is written in the comment right above:


// NaN意味着非代码点

// NaN means non-codepoint

因此必须先执行此比较以处理 NaN 在JavaScript中的情况:

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

NaN === NaN 返回 false

正如 James Wiseman所指出的同样重要的是要知道为什么开发人员使用 high!== high 而不是 isNaN(高)哪个会更清楚。

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.

这肯定是基于表现。 测试显示 a!== a isNaN(a) 快20倍

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

< a href =https://stackoverflow.com/users/497418/zzzzbov> zzzzBov 还表示可以使用<$覆盖 isNaN() c $ c>!== 也更便携。

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

来自 Benjamin Gruenbaum


同样值得注意的是NaN不等于任何东西否则为
,并且它不等于非严格意义上的任何其他内容

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

并且来自 Jan Dvorak


另请注意 {valueOf:function(){return {}}} 自相等

这篇关于jQuery源代码中的奇怪代码:var!== var? x:y;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆