javascript Jquery.each() 和 Array.prototype.forEach() 方法的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17489842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference in Jquery.each() and Array.prototype.forEach() method
提问by Maizere Pathak.Nepal
Is there any difference between Jquery.each() and Array.prototype.forEach() method since array.forEach() method can also be used to loop over array-like objects with length property.The only difference i see is placement of arguments ,what else can be the difference in them?
Jquery.each() 和 Array.prototype.forEach() 方法之间有什么区别,因为 array.forEach() 方法也可以用来循环遍历具有长度属性的类数组对象。我看到的唯一区别是参数的位置,它们之间还有什么区别?
I found this:
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
What i wan to know is ,do jquery.each() invokes function for object without length property??
我想知道的是,jquery.each() 是否为没有长度属性的对象调用函数?
回答by
Placement of arguments in the callback.
Quantity of arguments in the callback (The
.forEach()
gives you get a reference to the original collection.)Default
this
value in the callback. (In jQuery it's the current item, in.forEach()
it's the JavaScript default)Ability to manually set the
this
value in the callback. (jQuery doesn't give this option,.forEach()
lets you via a third argument.)Avoidance of non-defined properties on sparse Arrays. (The
.forEach()
avoids them, jQuery includes them.)
在回调中放置参数。
回调中的参数数量(这
.forEach()
使您可以获得对原始集合的引用。)this
回调中的默认值。(在 jQuery 中,它是当前项,在.forEach()
JavaScript 中是默认项)能够
this
在回调中手动设置值。(jQuery 没有提供这个选项,.forEach()
让你通过第三个参数。)避免在稀疏数组上使用未定义的属性。(
.forEach()
避免它们,jQuery 包含它们。)
They're very differently behaving methods. jQuery's doesn't make any attempt to be compliant with or complimentary of the standard behaviors.
他们的行为方式非常不同。jQuery 不会尝试符合或补充标准行为。
回答by RobG
In addition to Crazy Train's answer:
除了 Crazy Train 的回答:
What i wan to know is ,do jquery.each() invokes function for object without length property??
我想知道的是,jquery.each() 是否为没有长度属性的对象调用函数?
Read the source:
阅读来源:
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
...
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
}
...
}
}
return object;
},
So you can see if there is no length property, or it has the value undefined, then jQuery thinks it's a plain object and will do a for..in loop over the enumerable properties with no guard against inherited properties.
因此,您可以查看是否没有 length 属性,或者它的值是undefined,然后 jQuery 认为它是一个普通对象,并且将对可枚举属性执行 for..in 循环,而不会对继承的属性进行保护。