如何循环遍历 jQuery 中的数组?

问题描述:

我正在尝试遍历一个数组.我有以下代码:

I am trying to loop through an array. I have the following code:

 var currnt_image_list= '21,32,234,223';
 var substr = currnt_image_list.split(','); // array here

我正在尝试从数组中取出所有数据.有人能带领我走上正确的道路吗?

Am trying to get all the data out of the array. Can some one lead me in the right path please?


(更新:我的这里的其他答案更彻底地列出了非 jQuery 选项.下面的第三个选项,jQuery.each,虽然不在其中.)


(Update: My other answer here lays out the non-jQuery options much more thoroughly. The third option below, jQuery.each, isn't in it though.)

四个选项:

var i;
for (i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

或在 ES2015+ 中:

or in ES2015+:

for (let i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

优点:直截了当,不依赖于 jQuery,易于理解,在循环体内保留 this 的含义没有问题,没有不必要的开销函数调用(例如,在理论上更快,但实际上您必须拥有如此多的元素,因此您可能会遇到其他问题;详细信息).

Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of this within the body of the loop, no unnecessary overhead of function calls (e.g., in theory faster, though in fact you'd have to have so many elements that the odds are you'd have other problems; details).

从 ECMAScript5 开始,数组有一个 forEach 函数,可以很容易地遍历数组:

As of ECMAScript5, arrays have a forEach function on them which makes it easy to loop through the array:

substr.forEach(function(item) {
    // do something with `item`
});

文档链接

(注意:还有很多其他函数,不仅仅是 forEach;请参阅 答案详情参考上文.)

(Note: There are lots of other functions, not just forEach; see the answer referenced above for details.)

优点:声明性,如果您手头有手,可以为迭代器使用预建函数,如果您的循环体很复杂,函数调用的范围有时很有用,不需要 i 包含范围内的变量.

Advantages: Declarative, can use a prebuilt function for the iterator if you have one handy, if your loop body is complex the scoping of a function call is sometimes useful, no need for an i variable in your containing scope.

缺点:如果您在包含代码中使用 this 并且您想在 forEach 中使用 thiscode> 回调,你必须要么 A) 把它放在一个变量中,这样你就可以在函数中使用它,B) 将它作为第二个参数传递给 forEach 所以 forEach在回调期间将其设置为 this,或 C) 使用 ES2015+ 箭头函数,它关闭 this.如果你不做这些事情之一,在回调中 this 将是 undefined(在严格模式下)或全局对象(window) 松散模式.过去还有第二个缺点,即 forEach 并未得到普遍支持,但在 2018 年,您将遇到的唯一一个没有 forEach 的浏览器是 IE8(它也不能正确在那里填充).

Disadvantages: If you're using this in the containing code and you want to use this within your forEach callback, you have to either A) Stick it in a variable so you can use it within the function, B) Pass it as a second argument to forEach so forEach sets it as this during the callback, or C) Use an ES2015+ arrow function, which closes over this. If you don't do one of those things, in the callback this will be undefined (in strict mode) or the global object (window) in loose mode. There used to be a second disadvantage that forEach wasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEach is IE8 (and it can't be properly polyfilled there, either).

for (const s of substr) { // Or `let` if you want to modify it in the loop body
    // do something with `s`
}

有关其工作原理的详细信息,请参阅此答案顶部链接的答案.

See the answer linked at the top of this answer for details on how that works.

优点:简单、直接,为数组中的条目提供一个包含范围的变量(或常量,在上面).

Advantages: Simple, straightforward, offers a contained-scope variable (or constant, in the above) for the entry from the array.

缺点:任何版本的 IE 都不支持.

Disadvantages: Not supported in any version of IE.

jQuery.each(substr, function(index, item) {
    // do something with `item` (or `this` is also `item` if you like)
});

(文档链接)

优点:具有与 forEach 相同的所有优点,而且您知道它的存在,因为您使用的是 jQuery.

Advantages: All of the same advantages as forEach, plus you know it's there since you're using jQuery.

缺点:如果您在包含代码中使用 this,则必须将其粘贴在一个变量中,以便您可以在函数中使用它,因为 this 表示函数中的其他内容.

Disadvantages: If you're using this in the containing code, you have to stick it in a variable so you can use it within the function, since this means something else within the function.

你可以避免 this 的事情,通过使用 $.proxy:

You can avoid the this thing though, by either using $.proxy:

jQuery.each(substr, $.proxy(function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}, this));

...或Function#bind:

jQuery.each(substr, function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}.bind(this));

...或者在 ES2015(ES6")中,一个箭头函数:

...or in ES2015 ("ES6"), an arrow function:

jQuery.each(substr, (index, item) => {
    // do something with `item` (`this` is the same as it was outside)
});

做什么:

不要为此使用for..in(或者,如果您这样做,请采取适当的保护措施).你会看到人们说 to(实际上,这里有一个简单的答案是这样说的),但是 for..in 并没有做很多人认为它做的事情(它做了一些更有用的事情!).具体来说,for..in 循环遍历对象的可枚举属性名称(而不是数组的索引).由于数组是对象,并且它们唯一的可枚举属性默认是索引,因此它似乎在平淡的部署中工作.但这并不是一个安全的假设,您可以将其用于此目的.这是一个探索:http://jsbin.com/exohi/3

What NOT to do:

Don't use for..in for this (or if you do, do it with proper safeguards). You'll see people saying to (in fact, briefly there was an answer here saying that), but for..in does not do what many people think it does (it does something even more useful!). Specifically, for..in loops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. But it's not a safe assumption that you can just use it for that. Here's an exploration: http://jsbin.com/exohi/3

我应该软化上面的不要".如果您正在处理稀疏数组(例如,该数组共有 15 个元素,但由于某种原因,它们的索引散布在 0 到 150,000 的范围内,因此 length 为 150,001),如果您使用适当的保护措施,例如 hasOwnProperty 并检查属性名称确实是数字(请参阅上面的链接),for..in 可以是一个完全合理的避免大量不必要循环的方法,因为只会枚举填充的索引.

I should soften the "don't" above. If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length is 150,001), and if you use appropriate safeguards like hasOwnProperty and checking the property name is really numeric (see link above), for..in can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.