javascript – JQuery和Underscore“每个”保证数组的顺序?

前端之家收集整理的这篇文章主要介绍了javascript – JQuery和Underscore“每个”保证数组的顺序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 Javascript上阅读:Good Parts …

Since JavaScript’s arrays are really objects,the for in statement can be used to iterate over all of the properties of an array. Unfortunately,for in makes no guarantee about the order of the properties…

据我所知,“每个”功能都是基于in,那么JQuery和Underscore库中的每个函数是否会在数组迭代时保证顺序?我试图避免令人讨厌的标准.

先谢谢你.

解决方法

当迭代数组时,总是保证顺序.当你不经过重复(非数组)对象是没有保证的时候.数组依然是对象.

每个都不是一个for for for对象,而是用于数组类.该框架确定作业的正确循环并且应用相同的逻辑:数组迭代是有序的,而对象迭代不是.

下划线的来源:

var each = _.each = _.forEach = function (obj,iterator,context) {
        if (obj == null) return;
        if (nativeForEach && obj.forEach === nativeForEach) {
            obj.forEach(iterator,context);
        } else if (obj.length === +obj.length) {
            for (var i = 0,l = obj.length; i < l; i++) {
                if (i in obj && iterator.call(context,obj[i],i,obj) === breaker) return;
            }
        } else {
            for (var key in obj) {
                if (_.has(obj,key)) {
                    if (iterator.call(context,obj[key],key,obj) === breaker) return;
                }
            }
        }
    };

jQuery的来源:

each: function (object,callback,args) {
    var name,i = 0,length = object.length,isObj = length === undefined || jQuery.isFunction(object);
    if (args) {
        if (isObj) {
            for (name in object) {
                if (callback.apply(object[name],args) === false) {
                    break;
                }
            }
        } else {
            for (; i < length;) {
                if (callback.apply(object[i++],args) === false) {
                    break;
                }
            }
        }
        // A special,fast,case for the most common use of each
    } else {
        if (isObj) {
            for (name in object) {
                if (callback.call(object[name],name,object[name]) === false) {
                    break;
                }
            }
        } else {
            for (; i < length;) {
                if (callback.call(object[i],object[i++]) === false) {
                    break;
                }
            }
        }
    }
    return object;
}

猜你在找的jQuery相关文章