首页 > underscorejs源码解惑

underscorejs源码解惑

先附上源码:

_.indexOf = function(array, item, isSorted) {
    var i = 0, length = array && array.length;
    if (typeof isSorted == 'number') {
        i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
    } else if (isSorted && length) {
        i = _.sortedIndex(array, item);
        return array[i] === item ? i : -1;
    }
    if (item !== item) {
        return _.findIndex(slice.call(array, i), _.isNaN);
    }
    for (; i < length; i++) if (array[i] === item) return i;
    return -1;
};

if(item!==item) return _.findIndex(slice.call(array, i), _.isNaN)这里没明白是什么意思。自己不等于自己,难道item是NaN??


你自己都把答案写出来了,这里就是判断 NaN 的情况

    if (item !== item) {
        return _.findIndex(slice.call(array, i), _.isNaN);
    }

意思是如果 item 是 NaN,就通过 _.isNaN 来比较,而不是通过 === 来比较。

【热门文章】
【热门文章】