使用jQuery .each迭代关联数组 [英] Iterating an associative array with jQuery .each

查看:104
本文介绍了使用jQuery .each迭代关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题最重要的因素可能是我现在非常困倦.

Probably the most contributing factor for this question is that I am extremely sleepy right now.

我有一个要初始化的数组:

I have an array, which I initiate:

var cells = [];

然后我在其中添加一些值(jQuery对象),例如:

Then i put some values in it (jQuery objects), for example:

$("td").each(function () {
  var td = $(this);
  cells[td.attr("id")] = td;
});

现在是我的问题.这段代码:

And now my problem. This code:

$(cells).each(function (i) {
  console.log(this) // firebug console
});

完全不记录任何内容.当我将关联数组更改为普通数组时,用

logs absolutelly nothing. When i changed the associative array to a normal, number index one by substituting

cells[td.attr("id")] = td;

使用

cells.push(td);

它正常工作.

此外,当我尝试使用for..in循环进行迭代时,它会按预期工作.

Also, when I try to iterate with the for..in loop it works as expected.

for (var cell in cells) {
  console.log(cells[cell]);
}

这样做是否意味着jQuery的.each方法不接受关联数组,或者我做错了什么?

Doeas that mean that jQuery's .each method does not accept associative arrays or am I doing something wrong?

推荐答案

JavaScript没有关联数组.它具有数组,并且具有对象,而数组恰好是对象.当您这样做时:

JavaScript does not have associative arrays. It has Arrays and it has Objects, and arrays happen to be objects. When you do this:

var a = [];
a['foo'] = 'bar';

..您实际上正在执行以下操作:

..you're actually doing the equivalent of this:

var a = [];
a.foo = 'bar';
// ^--- property of object 'a'

也就是说,您实际上是在对象 a中添加名为foo属性,而不是添加元素数组 a.

That is to say you're actually adding a property called foo to the object a, not adding an element to the array a.

摘自 jQuery.each() 的文档:

From the documentation for jQuery.each():

具有length属性的数组和类似数组的对象(例如函数的arguments对象)通过从0length-1的数字索引进行迭代.其他对象通过其命名属性进行迭代.

Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

由于创建了Array([]),jQuery会查看其length属性,并且由于尚未向数组添加任何元素(仅在对象上添加了 properties ,请记住),它的length仍然为零,因此jQuery(正确)没有执行任何操作.

Since you created an Array ([]) jQuery looks at its length property, and since you have not added any elements to the array (only properties on the object, remember) its length is still zero and so jQuery (correctly) does nothing.

相反,您想做的就是使用例如var cells = {};.由于非数组对象没有length属性(无论如何默认情况下都不是默认属性),jQuery会知道您真的想遍历其 properties 而不是像Array中那样使用数字索引.

What you want to do instead, as others have noted, is create an Object using e.g. var cells = {};. Since a non-Array object has no length property (not by default, anyway) jQuery will know that you really want to iterate over its properties instead of numeric indices as in an Array.

这篇关于使用jQuery .each迭代关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆