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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3943494/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:46:08  来源:igfitidea点击:

How to loop through array in jQuery?

javascriptjqueryarraysloopsiteration

提问by Rickstar

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?

我试图从数组中获取所有数据。有人可以带领我走上正确的道路吗?

回答by T.J. Crowder



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

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



Four options:

四个选项:

Generic loop:

通用循环:

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

or in ES2015+:

或在 ES2015+ 中:

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

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

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

ES5's forEach:

ES5的forEach

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

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

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

Link to docs

链接到文档

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

(注意:还有很多其他功能,而不仅仅是forEach;有关详细信息,请参阅上面引用的答案。)

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 ivariable in your containing scope.

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

Disadvantages: If you're using thisin the containing code and you want to use thiswithin your forEachcallback, 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 forEachso forEachsets it as thisduring 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 thiswill be undefined(in strict mode) or the global object (window) in loose mode. There used to be a second disadvantage that forEachwasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEachis IE8 (and it can't be properlypolyfilled there, either).

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

ES2015+'s for-of:

ES2015+ 的for-of

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.

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

Disadvantages: Not supported in any version of IE.

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

jQuery.each:

jQuery.each:

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

(Link to docs)

链接到文档

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

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

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

缺点:如果你this在包含代码中使用,你必须把它放在一个变量中,这样你才能在函数中使用它,因为在函数中this意味着其他东西。

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

this不过,您可以通过使用$.proxy以下任一方法来避免这种情况:

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

...or Function#bind:

...或Function#bind

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

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

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

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

What NOTto do:

什么不该做:

Don'tuse for..infor 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..indoes not do what many people think it does (it does something even more useful!). Specifically, for..inloops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by defaultare 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

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

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 lengthis 150,001), andif you use appropriate safeguards like hasOwnPropertyand checking the property name is really numeric (see link above), for..incan be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.

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

回答by skyfoot

jQuery.each()

jQuery.each()

jQuery.each()

jQuery.each()

jQuery.each(array, callback)

array iteration

数组迭代

jQuery.each(array, function(Integer index, Object value){});

object iteration

对象迭代

jQuery.each(object, function(string propertyName, object propertyValue){});

example:

例子

var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) { 
  console.log(index, val)
});

var myObj = { firstName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
  console.log(propName, propVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript loops for array

数组的javascript循环

for loop

for循环

for (initialExpression; condition; incrementExpression)
  statement

example

例子

var substr = [1, 2, 3, 4];

//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
  console.log("loop", substr[i])
}

//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
  console.log("reverse", substr[i])
}

//step loop
for(var i = 0; i < substr.length; i+=2) {
  console.log("step", substr[i])
}

for in

因为在

//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
    console.log(substr[i]) //note i returns index
}

for of

对于的

for(var i of subs) {
    //can use break;
    console.log(i); //note i returns value
}

forEach

为每个

substr.forEach(function(v, i, a){
    //cannot use break;
    console.log(v, i, a);
})

Resources

资源

MDN loops and iterators

MDN 循环和迭代器

回答by Nick Craver

No need for jquery here, just a forloop works:

这里不需要 jquery,只需一个for循环即可:

var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
  alert(substr[i]);
}

回答by John Slegers

Option 1 : The traditional for-loop

选项 1:传统的for-loop

The basics

基础知识

A traditional for-loop has three components :

传统的for循环包含三个组件:

  1. the initialization :executed before the look block is executed the first time
  2. the condition :checks a condition every time before the loop block is executed, and quits the loop if false
  3. the afterthought :performed every time after the loop block is executed
  1. 初始化:在第一次执行look块之前执行
  2. 条件:每次执行循环块之前检查一个条件,如果为假则退出循环
  3. 事后思考:每次执行循环块后执行

These three components are seperated from each other by a ;symbol. Content for each of these three components is optional, which means that the following is the most minimal for-loop possible :

这三个组件由一个;符号相互隔开。这三个组件中的每一个的内容都是可选的,这意味着以下是最小的for-loop 可能:

for (;;) {
    // Do stuff
}

Of course, you will need to include an if(condition === true) { break; }or an if(condition === true) { return; }somewhere inside that for-loop to get it to stop running.

当然,您需要在该-loop 中if(condition === true) { break; }if(condition === true) { return; }某处包含一个或一个,for以使其停止运行。

Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index :

但是,通常初始化用于声明索引,条件用于将该索引与最小值或最大值进行比较,事后考虑用于增加索引:

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}


Using a tradtional for-loop to loop through an array

使用传统的for-loop 循环遍历数组

The traditional way to loop through an array, is this :

循环遍历数组的传统方法是:

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

Or, if you prefer to loop backwards, you do this :

或者,如果您更喜欢向后循环,您可以这样做:

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

There are, however, many variations possible, like eg. this one :

然而,有许多变化是可能的,例如。这个 :

for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

... or this one ...

……或者这个……

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... or this one :

...或这个:

var key = 0, value;
for (; value = myArray[key++];){ 
    console.log(value);
}

Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.

无论哪种效果最好,很大程度上取决于个人品味和您正在实施的特定用例。

Note :笔记 :

Each of these variations is supported by all browsers, including véry old ones!

所有浏览器都支持这些变体中的每一个,包括非常旧的浏览器!



Option 2 : The while-loop

选项 2:while-loop

One alternative to a for-loop is a while-loop. To loop through an array, you could do this :

for-loop 的一种替代方法是while-loop。要遍历数组,您可以这样做:

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}
Note :笔记 :

Like traditional for-loops, while-loops are supported by even the oldest of browsers.

与传统的for-loops一样,while即使是最古老的浏览器也支持 -loops。

Also, every while loop can be rewritten as a for-loop. For example, the while-loop hereabove behaves the exact same way as this for-loop :

此外,每个 while 循环都可以重写为 - 循环for。例如,while上面的-loop 的行为方式与这个for-loop完全相同:

for(var key = 0;value = myArray[key++];){
    console.log(value);
}


Option 3 : for...inand for...of

选项 3:for...infor...of

In JavaScript, you can also do this :

在 JavaScript 中,你也可以这样做:

for (i in myArray) {
    console.log(myArray[i]);
}

This should be used with care, however, as it doesn't behave the same as a traditonal for-loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea?for more details.

但是,这应该谨慎使用,因为它for在所有情况下的行为都与传统的-loop 不同,并且需要考虑潜在的副作用。请参阅为什么在数组迭代中使用“for...in”是个坏主意?更多细节。

As an alternative to for...in, there's now also for for...of. The following example shows the difference between a for...ofloop and a for...inloop :

作为 的替代for...in,现在还有 for for...of。以下示例显示了for...of循环和for...in循环之间的区别:

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7
}
Note :笔记 :

You also need to consider that no version of Internet Explorer supports for...of(Edge 12+does) and that for...inrequires at least IE10.

您还需要考虑没有任何版本的 Internet Explorer 支持for...ofEdge 12+支持)并且for...in至少需要 IE10。



Option 4 : Array.prototype.forEach()

选项 4: Array.prototype.forEach()

An alternative to For-loops is Array.prototype.forEach(), which uses the following syntax :

For-loops的替代方法是Array.prototype.forEach(),它使用以下语法:

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});
Note :笔记 :

Array.prototype.forEach()is supported by all modern browsers, as well as IE9+.

Array.prototype.forEach()所有现代浏览器以及 IE9+ 都支持。



Option 5 : jQuery.each()

选项 5: jQuery.each()

Additionally to the four other options mentioned, jQuery also had its own foreachvariation.

除了提到的其他四个选项,jQuery 也有自己的foreach变体。

It uses the following syntax :

它使用以下语法:

$.each(myArray, function(key, value) {
    console.log(value);
});

回答by Romain Linsolas

Use the each()function of jQuery.

使用each()jQuery的功能。

Here is an example:

下面是一个例子:

$.each(currnt_image_list.split(','), function(index, value) { 
  alert(index + ': ' + value); 
});

回答by MItrajyoti Kusari

Use jQuery each(). There are other ways but each is designed for this purpose.

使用 jQuery each()。还有其他方法,但每种方法都是为此目的而设计的。

$.each(substr, function(index, value) { 
  alert(value); 
});

And do not put the comma after the last number.

并且不要在最后一个数字后面放逗号。

回答by SLaks

You can use a for()loop:

您可以使用for()循环:

var things = currnt_image_list.split(','); 
for(var i = 0; i < things.length; i++) {
    //Do things with things[i]
}

回答by usman tahir

ES6 syntax with arrow function and interpolation:

带有箭头函数和插值的 ES6 语法:

var data=["a","b","c"];
$(data).each((index, element) => {
        console.log(`current index : ${index} element : ${element}`)
    });

回答by usman tahir

Try this:

尝试这个:

$.grep(array, function(element) {

})

回答by Kamil Kie?czewski

Alternative ways of iteration through array/string with side effects

通过具有副作用的数组/字符串进行迭代的替代方法

var str = '21,32,234,223';
var substr = str.split(',');

substr.reduce((a,x)=> console.log('reduce',x), 0)        // return undefined

substr.every(x=> { console.log('every',x); return true}) // return true

substr.some(x=> { console.log('some',x); return false})  // return false

substr.map(x=> console.log('map',x));                    // return array
 
str.replace(/(\d+)/g, x=> console.log('replace',x))      // return string