jQuery.each() 如何处理关联数组(对象)?

发布于 2024-11-14 20:01:31 字数 188 浏览 3 评论 0原文

我有一个关联数组,里面有两个对象。通过 $(myassoc).each() 运行此回调,回调仅运行一次。回调参数(索引和对象)也分别返回 0 和整个关联数组。

人们期望 jQuery.each() 为数组中的每个元素运行,返回正确的键作为索引,返回正确的元素作为对象。

为什么这种情况没有发生,jQuery 可以做我想要的事情吗?

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.

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.

Why isn't that happening, and can jQuery do what I'm after?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寄风 2024-11-21 20:01:31

我认为您正在寻找 jQuery.each() 而不是 .each()

试试这个:

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

I think you're looking for jQuery.each() instead of .each()

try this:

    $.each(myassoc, function(index, value){
      //your code
    });
违心° 2024-11-21 20:01:31

试试这个:

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

try this:

$.each(assocarray,function(i, value){
  console.log('index: ' + i + ',value: ' + value);
});
故事还在继续 2024-11-21 20:01:31

糟糕的是。

不要 $(associative_array).each(function () {...}) —— 那是 废话

不要 $.each(associative_array, function() {...}); -- 有一个晦涩的 bug(1)

要查看该错误,请尝试this 在 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)

第一个示例输出三行键值对,正如它应该的那样。第二个没有输出!

这个故事的寓意是,不要在对象上使用 jQuery.each()。 (JavaScript 中的对象本质上与关联数组相同。)事情可能永远工作正常,但你运行有一天,一个对象碰巧有一个名为 length 的成员,并且它的值恰好是 0,然后你会突然出现一个很难修复的错误。解释。 (我会让你猜,通过这个答案的沉重分量,这是否发生在我身上。)

正如 错误报告

如果您需要迭代具有 length 属性的对象的所有键,jQuery.each 不是正确的解决方案。

我建议更进一步,永远不要依赖 jQuery.each 来实现关联数组。

(1) 这个“bug”可能永远不会被修复,因为 $.each() 历史上使用 Duck在数组上键入:“具有长度属性的数组和类似数组的对象(例如函数的参数对象)通过数字索引进行迭代。”


这是我使用的[感谢 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({foo:1, length:0, bar:2}, console.log)
  foo 1
  length 0
  bar 2

looper() 是 $.each() 就像 $.each() 一样:

  • 在回调内部,this
  • 回调内部的每个值,返回 false (不仅仅是 falsy ) 终止循环。
  • Looper() 返回最初传递给它的对象
  • 。 Looper() 适用于数组和对象。

使用:

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());

用 $.each() 尝试一下,你会得到一个空结果。因为它将这个特定对象解释为长度为零的类似数组的对象。

Badly.

Don't $(associative_array).each(function () {...}) -- that's nonsense

Don't $.each(associative_array, function() {...}); -- that has an obscure bug(1)

To see the bug, try this in a javascript console:

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

I suggest going further, that jQuery.each should not be relied upon for associative arrays, ever.

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


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:

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({foo:1, length:0, bar:2}, console.log)
  foo 1
  length 0
  bar 2

Just like $.each():

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

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.

夏の忆 2024-11-21 20:01:31

问题在于 $.each() 函数在内部检索并使用传递集合的 length 属性。但在没有整数索引的关联数组中,长度似乎总是0。对于 $.each() 现在似乎没有什么可遍历的。

$.each() 函数内部检索并使用长度
传递的集合的属性。

解决方案很简单,就是使用一个对象来代替。

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

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 indices the length always seems to be 0. For $.each() now there seems to be nothing to walk through.

The $.each() function internally retrieves and uses the length
property of the passed collection.

The solutions is simply to use an object instead.

var obj = {
  "flammable": "inflammable",
  "duh": "no duh"
};
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文