简体   繁体   English

jQuery.each() 如何与关联的 arrays(对象)一起使用?

[英]How does jQuery.each() work with associative arrays (objects)?

I have an associative array with two object inside.我有一个关联数组,里面有两个 object。 Running this through $(myassoc).each() , the callback runs only once.通过$(myassoc).each()运行它,回调只运行一次。 Also the callback parameters (index and object) returns 0 and the entire associative array, respectively.回调参数(索引和对象)也分别返回 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()为数组中的每个元素运行,返回正确的键作为索引,返回正确的元素作为 object。

Why isn't that happening, and can jQuery do what I'm after?为什么没有发生这种情况,jQuery 可以做我想要的吗?

I think you're looking for jQuery.each() instead of.each()我认为您正在寻找jQuery.each()而不是.each()

try this:尝试这个:

    $.each(myassoc, function(index, value){
      //your code
    });

try this:尝试这个:

$.each(assocarray,function(i, value){
  console.log('index: ' + i + ',value: ' + value);
});

Badly.很糟糕。

Don't $(associative_array).each(function () {...}) -- that's nonsense不要$(associative_array).each(function () {...}) - 这是胡说八道

Don't $.each(associative_array, function() {...});不要$.each(associative_array, function() {...}); -- that has an obscure bug (1) -- 有一个不为人知的错误(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 上使用 jQuery.each() (Objects in JavaScript are essentially the same thing as 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. (JavaScript 中的对象与关联 arrays 中的对象本质上相同的。)事情可能永远正常工作,但是你冒着有一天length恰好有一个名为的成员的错误0 ,然后它恰好有一个错误值不知从何而来,这可能很难解释。 (I'll let you guess, by the ponderous heft of this answer, whether that ever happened to me.) (我会让你猜,这个答案的分量很重,这是否发生在我身上。)

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.如果您需要遍历具有长度属性的对象的所有键,jQuery.each 不是正确的解决方案。

I suggest going further, that jQuery.each should not be relied upon for associative arrays, ever.我建议更进一步,永远不要依赖 jQuery.each 来关联 arrays。

(1) This "bug" may never be fixed, since $.each() historically uses Duck Typing on arrays: "Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index." (1) 这个“错误”可能永远无法修复,因为 $.each() 历史上在 arrays 上使用Duck Typing :“具有长度属性的数组和类似数组的对象(例如函数的 arguments 对象)由数字索引迭代。 "


Here's what I use [thanks Dominik ] to loop through property names and values of objects, or put another way, the keys and values of an associative array:下面是我使用[thanks 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

Just like $.each() :就像 $.each()

  • Inside the callback, this is each value在回调内部, this是每个值
  • Inside the callback, returning false (not just falsy) terminates the loop在回调内部,返回false (不仅仅是 falsy)会终止循环
  • looper() returns the object originally passed to it looper() 返回最初传递给它的 object
  • looper() works on arrays as well as objects. looper() 适用于 arrays 以及对象。

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.用 $.each() 试试,你会得到一个空的结果。 Because it interprets this particular object as an array-like object of zero length.因为它将这个特定的 object 解释为一个长度为零的类似数组的 object。

The problem is that the $.each() function internally retrieves and uses the length property of the passed collection.问题是$.each() function 在内部检索并使用传递集合的length属性。 But in an associative array that has no integer indices the length always seems to be 0 .但是在没有 integer 索引的关联数组中, length似乎总是0 For $.each() now there seems to be nothing to walk through.对于$.each()现在似乎没有什么可走的了。

The $.each() function internally retrieves and uses the length property of the passed collection. $.each() function 在内部检索并使用传递集合的length属性。

The solutions is simply to use an object instead.解决方案只是使用 object 代替。

var obj = {
  "flammable": "inflammable",
  "duh": "no duh"
};
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM