Javascript jQuery.each() 如何处理关联数组(对象)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6276207/
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
How does jQuery.each() work with associative arrays (objects)?
提问by Hubro
I have an associative array with two object inside. Running this through $(myassoc).each()
, the callback runs only once. Also the callback parameters (index and object) returns 0 and the entire associative array, respectively.
我有一个内部有两个对象的关联数组。运行这个通过$(myassoc).each()
,回调只运行一次。此外,回调参数(索引和对象)分别返回 0 和整个关联数组。
One would expect jQuery.each()
to run for each element in the array, returning the correct keys as index and the correct element as the object.
人们期望jQuery.each()
为数组中的每个元素运行,返回正确的键作为索引和正确的元素作为对象。
Why isn't that happening, and can jQuery do what I'm after?
为什么没有发生这种情况,jQuery 可以做我想做的事吗?
回答by dapangro
I think you're looking for jQuery.each()instead of .each()
我认为您正在寻找jQuery.each()而不是 .each()
try this:
尝试这个:
$.each(myassoc, function(index, value){
//your code
});
回答by thecodeparadox
try this:
尝试这个:
$.each(assocarray,function(i, value){
console.log('index: ' + i + ',value: ' + value);
});
回答by Bob Stein
Badly.
糟糕。
Don't $(associative_array).each(function () {...})
-- that's nonsense
不要$(associative_array).each(function () {...})
——那是胡说八道
Don't $.each(associative_array, function() {...});
-- that has an obscure bug(1)
不要$.each(associative_array, function() {...});
- 那有一个不起眼的错误(1)
To see the bug, try this in a javascript console:
要查看错误,请在 javascript 控制台中尝试此操作:
> $.each({foo:1, length:-1, bar:2}, console.log)
foo 1
length -1
bar 2
> $.each({foo:1, length:0, bar:2}, console.log)
The first example outputs three lines of key-value pairs, as it should. The second outputs nothing!
第一个示例输出三行键值对,正如它应该的那样。第二个什么都不输出!
The moral of the story, don't use jQuery.each() on objects. (Objects in JavaScript are essentiallythe same thingas associative arrays.) Things may work fine forever, but you run the risk that someday an object happens to have a member named length
and its value happens to be exactly 0
and then you have a bug out of nowhere that can be very difficult to explain. (I'll let you guess, by the ponderous heft of this answer, whether that ever happened to me.)
这个故事的寓意是,不要在 objects 上使用 jQuery.each()。(JavaScript 中的对象本质上与关联数组是一样的。)事情可能会永远运行良好,但你会冒这样的风险,某天某个对象碰巧有一个命名的成员length
并且它的值碰巧恰好是0
,然后你就会有一个错误没有什么地方是很难解释的。(我会让你猜测,通过这个答案的沉重,我是否曾经发生过这种情况。)
As mentioned in the bug report:
如错误报告中所述:
If you need to iterate over all keys of objects having the length property, jQuery.each is not the correct solution.
如果您需要遍历具有 length 属性的对象的所有键,jQuery.each 不是正确的解决方案。
I suggest going further, that jQuery.each should not be relied upon for associative arrays, ever.
我建议更进一步,永远不应该依赖 jQuery.each 作为关联数组。
(1) This "bug" may never be fixed, since $.each() historically uses Duck Typingon arrays: "Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index."
(1) 这个“错误”可能永远不会被修复,因为 $.each() 历史上在数组上使用Duck Typing:“数组和具有长度属性的类数组对象(例如函数的参数对象)通过数字索引进行迭代。 ”
Here's what I use[thanks Dominik]to loop through property names and valuesof objects, or put another way, the keys and values of an associative array:
这是我使用[感谢Dominik]来循环遍历对象的属性名称和值,或者换句话说,关联数组的键和值的内容:
function looper(object, callback) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
if (false === callback.call(object[key], key, object[key])) {
break;
}
}
}
return object;
}
looper() is then a drop-in replacement for $.each()
looper() 然后是 $.each() 的替代品
> looper({foo:1, length:0, bar:2}, console.log)
foo 1
length 0
bar 2
- Inside the callback,
this
is each value - Inside the callback, returning
false
(not just falsy) terminates the loop - looper() returns the object originally passed to it
- looper() works on arrays as well as objects.
- 在回调内部,
this
是每个值 - 在回调内部,返回
false
(不仅仅是假)终止循环 - looper() 返回最初传递给它的对象
- looper() 适用于数组和对象。
Use:
用:
var a = [];
looper({foo:1, length:0, bar:2}, function(k, v) {
a.push(k+"="+v);
});
console.assert("foo=1,length=0,bar=2" === a.join());
Try that with $.each() and you'll get an empty result. Because it interprets this particular object as an array-like object of zero length.
用 $.each() 试试,你会得到一个空的结果。因为它将这个特定对象解释为一个零长度的类数组对象。
回答by leymannx
The problem is that the $.each()
function internally retrieves and uses the length
property of the passed collection. But in an associative array that has no integer indicesthe length
always seems to be 0
. For $.each()
now there seems to be nothing to walk through.
问题在于该$.each()
函数在内部检索并使用length
传递的集合的属性。但是在没有整数索引的关联数组中,length
似乎总是0
. 对于$.each()
目前来说,似乎是没什么通过行走。
The
$.each()
function internally retrieves and uses thelength
property of the passed collection.
该
$.each()
函数在内部检索并使用length
传递的集合的属性。
The solutions is simply to use an object instead.
解决方案只是使用一个对象来代替。
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});