简体   繁体   English

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

[英]How to loop through array in 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?有人可以带领我走上正确的道路吗?


(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.) (更新:我在这里的另一个答案更彻底地列出了非 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 this within the body of the loop, no unnecessary overhead of function calls (eg, in theory faster, 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 forEach function 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 above for 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 i variable in your containing scope.优点:声明性,如果你有手,可以为迭代器使用预建函数,如果你的循环体很复杂,函数调用的范围有时是有用的,在你的包含范围中不需要i变量。

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 .缺点:如果您在使用this中包含代码,你想用this你中forEach回调,你必须要么A)坚持在一个变量,所以你可以在函数中使用它,B),将它作为第二forEach参数因此forEach在回调期间将其设置为this ,或者 C) 使用 ES2015+箭头函数,它关闭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.如果你不做这些事情之一,在回调中this将是undefined (在严格模式下)或全局对象( window )在松散模式下。 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).曾经有第二个缺点,即forEach并未得到普遍支持,但在 2018 年,您将遇到的唯一没有forEach浏览器是 IE8(并且在那里也无法正确填充) )。

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 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 ,则必须将其粘贴在变量中,以便您可以在函数中使用它,因为this意味着函数中的其他内容。

You can avoid the this thing though, by either using $.proxy :你可以通过使用$.proxy来避免this事情:

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 NOT to do:什么不该做:

Don't use for..in for this (or if you do, do it with proper safeguards).不要为此使用for..in (或者,如果你这样做了,请采取适当的保护措施)。 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!).你会看到人们说 to(事实上,这里有一个简单的答案是这样说的),但是for..in并没有像很多人认为的那样做(它做了一些更有用的事情!)。 Specifically, for..in loops through the enumerable property names of an object (not the indexes of an array).具体来说, for..in循环for..in对象的可枚举属性名称(而不是数组的索引)。 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这是一个探索: http : //jsbin.com/exohi/3

I should soften the "don't" above.我应该软化上面的“不要”。 If you're dealing with sparse arrays (eg, 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.如果您正在处理稀疏数组(例如,该数组共有 15 个元素,但由于某种原因它们的索引散布在 0 到 150,000 的范围内,因此length为 150,001),并且如果您使用适当的保护措施,例如hasOwnProperty和检查属性名称确实是数字(参见上面的链接), for..in是避免大量不必要循环的一种非常合理的方法,因为只会枚举填充的索引。

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 循环和迭代器

No need for jquery here, just a for loop works:这里不需要 jquery,只需一个for循环即可:

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

Option 1 : The traditional for -loop选项 1:传统的for循环

The basics基础知识

A traditional for -loop has three components :传统的for循环包含三个组件:

  1. the initialization : executed before the look block is executed the first time初始化:在第一次执行look块之前执行
  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事后思考:每次执行循环块后执行

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; }当然,你需要包含一个if(condition === true) { break; } if(condition === true) { break; } or an if(condition === true) { return; } if(condition === true) { break; }或者一个if(condition === true) { return; } if(condition === true) { return; } somewhere inside that for -loop to get it to stop running. if(condition === true) { return; }内某处for -loop得到它停止运行。

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循环遍历数组

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循环

One alternative to a for -loop is a while -loop. for循环的一种替代方法是while循环。 To loop through an array, you could do this :要遍历数组,您可以这样做:

 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.此外,每个 while 循环都可以重写为for循环。 For example, the while -loop hereabove behaves the exact same way as this for -loop :例如,上面的while -loop 的行为方式与for -loop 完全相同:

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

Option 3 : for...in and 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.但是,这应该谨慎使用,因为它在所有情况下的行为都与传统的for循环不同,并且需要考虑潜在的副作用。 See Why is using "for...in" with array iteration a bad idea?请参阅为什么在数组迭代中使用“for...in”是个坏主意? for more details.了解更多详情。

As an alternative to for...in , there's now also for for...of .作为for...in的替代,现在还有for...of The following example shows the difference between a for...of loop and a for...in loop :以下示例显示了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...in requires 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循环的替代方法是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+.所有现代浏览器以及 IE9+ 都支持Array.prototype.forEach()


Option 5 : jQuery.each()选项 5: jQuery.each()

Additionally to the four other options mentioned, jQuery also had its own foreach variation.除了提到的其他四个选项,jQuery 也有自己的foreach变体。

It uses the following syntax :它使用以下语法:

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

Use the each() function of jQuery.使用 jQuery 的each()函数。

Here is an example:下面是一个例子:

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

Use jQuery each() .使用 jQuery each() There are other ways but each is designed for this purpose.还有其他方法,但每种方法都是为此目的而设计的。

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

And do not put the comma after the last number.并且不要在最后一个数字后面放逗号。

ES6 syntax with arrow function and interpolation:带有箭头函数和插值的 ES6 语法:

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

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]
}

Try this:试试这个:

$.grep(array, function(element) {

})

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

  for(var key in substr)
{
     // do something with substr[key];

} 

$.map(data,function(elem) {...}) $.map(data,function(elem) {...})

$.map(data,function(elem){
   console.log(elem);
})
            
   

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

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