javascript - underscorejs源码解惑

查看:93
本文介绍了javascript - 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 来比较,而不是通过 === 来比较。

这篇关于javascript - underscorejs源码解惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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