令人困惑的 if jQuery 合并函数中的条件

Perplexing if condition in jQuery merge function

我刚刚浏览了 jQuery 的代码并遇到了函数合并。我查看了这个函数的代码:

merge: function( first, second ) {
    var len = +second.length,
        j = 0,
        i = first.length;

    while ( j < len ) {
        first[ i++ ] = second[ j++ ];
    }

    // Support: IE<9
    // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)

    if ( len !== len ) {
        while ( second[j] !== undefined ) {
            first[ i++ ] = second[ j++ ];
        }
    }

    first.length = i;

    return first;
},

现在,如果您浏览代码,您会遇到以下 if 检查:

if ( len !== len )

这在某种程度上对我来说没有意义,这个检查到底是为了什么,它在做什么?

len 上面几行定义的很清楚,像这样:

var len = +second.length;

那么为什么有人要检查是否 len !== len?这在某种程度上对我来说没有意义。有人可以解释吗?

这是对 NaN 的检查(正如@Jonathan 的评论中正确指出的那样)。来自优秀Mozilla documentation:

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

赋值 var len = +second.length; 中的 + 运算符 (unary plus) 试图通过内部调用 valueOf()toString()。如果转换为数字失败,它会将 NaN 赋值给变量 len。如前所述,len !== len 是一种检查 NaN.

的方法