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

Ric*_*tar 222 javascript arrays iteration jquery loops

我试图循环一个数组.我有以下代码:

 var currnt_image_list= '21,32,234,223';
 var substr = currnt_image_list.split(','); // array here
Run Code Online (Sandbox Code Playgroud)

我试图从阵列中获取所有数据.有人可以带我走正确的道路吗?

T.J*_*der 488


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


四种选择:

通用循环:

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

或者在ES2015 +中:

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

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

ES5 forEach:

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

substr.forEach(function(item) {
    // do something with `item`
});
Run Code Online (Sandbox Code Playgroud)

链接到文档

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

优点:声明性,如果你有一个方便的话可以使用迭代器的预构建函数,如果你的循环体很复杂,函数调用的范围有时是有用的,不需要i在包含范围内的变量.

缺点:如果你使用this的包含代码,你想用this你的内forEach回调,你必须要么A)坚持在一个变量,所以你可以在函数中使用它,B),将它作为第二个参数forEach等等forEach将其设置为this回调期间,或C)使用ES2015 + 箭头功能,该功能将关闭this.如果你不做其中的一件事,那么回调this将是undefined(在严格模式下)或window松散模式下的全局对象().曾经有一个第二个缺点,forEach并没有普遍支持,但在2018年,你将遇到的唯一一个没有的浏览器forEach是IE8(它不能正常使用) 在那里多层填充,或).

ES2015 +的for-of:

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

请参阅本答案顶部链接的答案,详细了解其工作原理.

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

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

jQuery.each:

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

(链接到文档)

优点:所有相同的优点forEach,加上你知道它就在那里,因为你正在使用jQuery.

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

你可以通过以下方式避免这种this情况$.proxy:

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

......或者Function#bind:

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

......或在ES2015("ES6")中,箭头功能:

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

什么不该做:

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

我应该软化上面的"不要".如果你有稀疏阵列处理(例如,阵列总共有15个元素,但它们的索引在范围为0散落150,000出于某种原因,所以length是150,001),并且如果使用适当的保障措施一样hasOwnProperty,并检查属性名称实际上是数字(参见上面的链接),for..in可以是避免大量不必要循环的完美合理方法,因为只会枚举填充的索引.


sky*_*oot 72

jQuery.each()

jQuery.each()

jQuery.each(array, callback)
Run Code Online (Sandbox Code Playgroud)

数组迭代

jQuery.each(array, function(Integer index, Object value){});
Run Code Online (Sandbox Code Playgroud)

对象迭代

jQuery.each(object, function(string propertyName, object propertyValue){});
Run Code Online (Sandbox Code Playgroud)

例如:

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);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

数组的javascript循环

for循环

for (initialExpression; condition; incrementExpression)
  statement
Run Code Online (Sandbox Code Playgroud)

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])
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

因为

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

的forEach

substr.forEach(function(v, i, a){
    //cannot use break;
    console.log(v, i, a);
})
Run Code Online (Sandbox Code Playgroud)

资源

MDN循环和迭代器


Nic*_*ver 20

这里不需要jquery只是for循环工作:

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


Joh*_*ers 18

选项1:传统的for循环

基础

传统的for循环有三个组成部分:

  1. 初始化:在第一次执行look块之前执行
  2. 条件:每次执行循环块之前检查一个条件,如果为false则退出循环
  3. 事后的想法:每次执行循环块后执行

这三个组件通过;符号彼此分开.这三个组件中的每一个的内容都是可选的,这意味着以下是最小的for-loop:

for (;;) {
    // Do stuff
}
Run Code Online (Sandbox Code Playgroud)

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

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

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}
Run Code Online (Sandbox Code Playgroud)

使用tradtional for-loop循环遍历数组

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

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

或者,如果您希望向后循环,则执行以下操作:

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}
Run Code Online (Sandbox Code Playgroud)

然而,存在许多可能的变化,例如.这个 :

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

......或者这一个......

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

......或者这个:

var key = 0, value;
for (; value = myArray[key++];){ 
    console.log(value);
}
Run Code Online (Sandbox Code Playgroud)

无论哪种效果最好,主要取决于个人品味和您正在实施的具体用例.

注意 :

所有浏览器都支持这些变体,包括véry旧的浏览器!


选项2:while-loop

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

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}
Run Code Online (Sandbox Code Playgroud) 注意 :

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

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

for(var key = 0;value = myArray[key++];){
    console.log(value);
}
Run Code Online (Sandbox Code Playgroud)

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

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

for (i in myArray) {
    console.log(myArray[i]);
}
Run Code Online (Sandbox Code Playgroud)

然而,这应该谨慎使用,因为它for在所有情况下都不像传统环路那样,并且存在需要考虑的潜在副作用.看看为什么在数组迭代中使用"for ... in"是一个坏主意?更多细节.

作为替代方案for...in,现在也有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
}
Run Code Online (Sandbox Code Playgroud) 注意 :

您还需要考虑Internet Explorer不支持任何版本for...of(Edge 12+),并且for...in至少需要IE10.


选项4: Array.prototype.forEach()

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

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});
Run Code Online (Sandbox Code Playgroud) 注意 :

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


选项5: jQuery.each()

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

它使用以下语法:

$.each(myArray, function(key, value) {
    console.log(value);
});
Run Code Online (Sandbox Code Playgroud)


Rom*_*las 17

使用each()jQuery 的功能.

这是一个例子:

$.each(currnt_image_list.split(','), function(index, value) { 
  alert(index + ': ' + value); 
});
Run Code Online (Sandbox Code Playgroud)


小智 6

每个都使用Jquery.还有其他方法,但每个方法都是为此目的而设计的.

$.each(substr, function(index, value) { 
  alert(value); 
});
Run Code Online (Sandbox Code Playgroud)

并且不要将逗号放在最后一个数字之后.


小智 6

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

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