簡體   English   中英

如何循環遍歷 jQuery 中的數組?

[英]How to loop through array in jQuery?

我正在嘗試遍歷一個數組。 我有以下代碼:

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

我試圖從數組中獲取所有數據。 有人可以帶領我走上正確的道路嗎?


(更新:我在這里的另一個答案更徹底地列出了非 jQuery 選項。不過,下面的第三個選項jQuery.each不在其中。)


四個選項:

通用循環:

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

或在 ES2015+ 中:

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

優點:直接,不依賴於 jQuery,易於理解,在循環體中保留this的含義沒有問題,沒有不必要的函數調用開銷(例如,理論上更快,但實際上你會有有這么多元素,你很可能會遇到其他問題; 細節)。

ES5 的forEach

從 ECMAScript5 開始,數組有一個forEach函數,這使得遍歷數組變得容易:

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

鏈接到文檔

(注意:還有很多其他函數,而不僅僅是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`
}

有關其工作原理的詳細信息,請參閱此答案頂部鏈接的答案。

優點:簡單、直接,為數組中的條目提供了一個包含范圍的變量(或常量,在上面)。

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

jQuery.each:

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

鏈接到文檔

優點:具有與forEach相同的所有優點,而且您知道它的存在,因為您使用的是 jQuery。

缺點:如果您在包含代碼中使用this ,則必須將其粘貼在變量中,以便您可以在函數中使用它,因為this意味着函數中的其他內容。

你可以通過使用$.proxy來避免this事情:

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”)中,一個箭頭函數:

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

什么不該做:

不要為此使用for..in (或者,如果你這樣做了,請采取適當的保護措施)。 你會看到人們說 to(事實上,這里有一個簡單的答案是這樣說的),但是for..in並沒有像很多人認為的那樣做(它做了一些更有用的事情!)。 具體來說, for..in循環for..in對象的可枚舉屬性名稱(而不是數組的索引)。 由於數組是對象,並且默認情況下它們唯一可枚舉的屬性是索引,因此它似乎主要是在平淡的部署中工作。 但這並不是一個安全的假設,您可以將其用於此目的。 這是一個探索: http : //jsbin.com/exohi/3

我應該軟化上面的“不要”。 如果您正在處理稀疏數組(例如,該數組共有 15 個元素,但由於某種原因它們的索引散布在 0 到 150,000 的范圍內,因此length為 150,001),並且如果您使用適當的保護措施,例如hasOwnProperty和檢查屬性名稱確實是數字(參見上面的鏈接), for..in是避免大量不必要循環的一種非常合理的方法,因為只會枚舉填充的索引。

jQuery.each()

jQuery.each()

jQuery.each(array, callback)

數組迭代

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

對象迭代

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

例子

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

for循環

for (initialExpression; condition; incrementExpression)
  statement

例子

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

因為在

//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(var i of subs) {
    //can use break;
    console.log(i); //note i returns value
}

為每個

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

資源

MDN 循環和迭代器

這里不需要 jquery,只需一個for循環即可:

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

選項 1:傳統的for循環

基礎知識

傳統的for循環包含三個組件:

  1. 初始化:在第一次執行look塊之前執行
  2. 條件:每次執行循環塊之前檢查一個條件,如果為假則退出循環
  3. 事后思考:每次執行循環塊后執行

這三個組件由一個;相互隔開; 符號。 這三個組件中的每一個的內容都是可選的,這意味着以下是最小的for -loop 可能:

for (;;) {
    // Do stuff
}

當然,你需要包含一個if(condition === true) { break; } if(condition === true) { break; }或者一個if(condition === true) { return; } if(condition === true) { return; }內某處for -loop得到它停止運行。

但是,通常初始化用於聲明索引,條件用於將該索引與最小值或最大值進行比較,事后考慮用於增加索引:

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

使用傳統的for循環遍歷數組

循環遍歷數組的傳統方法是:

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

或者,如果你更喜歡向后循環,你可以這樣做:

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

然而,有許多變化是可能的,例如。 這個:

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

……或者這個……

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

...或這個:

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

無論哪種效果最好,很大程度上取決於個人品味和您正在實施的特定用例。

注意:

所有瀏覽器都支持這些變體中的每一個,包括非常舊的瀏覽器!


選項 2: while循環

for循環的一種替代方法是while循環。 要遍歷數組,您可以這樣做:

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

與傳統的for -loops 一樣, while -loops 甚至被最古老的瀏覽器支持。

此外,每個 while 循環都可以重寫為for循環。 例如,上面的while -loop 的行為方式與for -loop 完全相同:

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

選項 3: for...infor...of

在 JavaScript 中,你也可以這樣做:

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

但是,這應該謹慎使用,因為它在所有情況下的行為都與傳統的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 }
注意:

您還需要考慮沒有任何版本的 Internet Explorer 支持for...ofEdge 12+支持),而for...in至少需要 IE10。


選項 4: Array.prototype.forEach()

For循環的替代方法是Array.prototype.forEach() ,它使用以下語法:

 myArray.forEach(function(value, key, myArray) { console.log(value); });
注意:

所有現代瀏覽器以及 IE9+ 都支持Array.prototype.forEach()


選項 5: jQuery.each()

除了提到的其他四個選項,jQuery 也有自己的foreach變體。

它使用以下語法:

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

使用 jQuery 的each()函數。

下面是一個例子:

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

使用 jQuery each() 還有其他方法,但每種方法都是為此目的而設計的。

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

並且不要在最后一個數字后面放逗號。

帶有箭頭函數和插值的 ES6 語法:

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

您可以使用for()循環:

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

試試這個:

$.grep(array, function(element) {

})

通過具有副作用的數組/字符串進行迭代的替代方法

 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){
   console.log(elem);
})
            
   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM