gpt4 book ai didi

javascript - JQuery 和 Underscore "each"保证数组的顺序?

转载 作者:可可西里 更新时间:2023-11-01 02:19:03 25 4
gpt4 key购买 nike

我阅读了 Javascript:好的部分...

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...

据我所知,“each”函数基于 for in,然后 each 函数是否形成 JQuery 和 Underscore 库在遍历数组时保证顺序?我试图避免使用烦人的标准 for

提前谢谢你。

最佳答案

当遍历数组时,顺序总是有保证的。当您遍历(非数组)对象时,就无法保证。顺便说一句,数组仍然是对象。


each 只不过是对象的 for in 和类数组的 for。框架为作业确定正确的循环并应用相同的逻辑:数组迭代是有序的,而对象迭代不是。

Underscore 的来源:

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], i, object[i++]) === false) {
break;
}
}
}
}
return object;
}

关于javascript - JQuery 和 Underscore "each"保证数组的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10740162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com