JS中對List、Map的各種遍歷方式 lambda


JS中對List、Map的各種遍歷方式

var list1 = ["number","name"];
var list2 = ["36","Crown","15","Faker","Swift","68","Dandy"];
var map_demo = { name: "John", lang: "JS" };

1.最常用的for循環

for(var i=0;i<list2.length;i++){
        console.info(i +":"+ list2 [i]);
}

小結:很常見也很常用,效率也不差,但不能遍歷map。

2.for...in...遍歷List/map

復制代碼
//遍歷map
for(var key in map_demo){
        console.info(key+":"+map_demo[key]);
}
//遍歷List
for(var index in list2){
        console.info(index+":"+list2[index]);

}

復制代碼

小結:對於List來說,能不用for...in就不要用,效率低下。

3.forEach遍歷List

復制代碼
list2.forEach(function (element, index, array) {
        console.info(element); //當前元素的值
        console.info(index);   //當前下標
        console.info(array);  //數組本身 

});
復制代碼

 

小結:和for循環效率差不多。

4.$.each()遍歷List/map

復制代碼
//遍歷List
$.each(list2,function(index,items){
        console.info(index+":"+items);
});
//遍歷map
$.each(map_demo,function(key,value){
        console.info("key: " + key + ", Value: " + value );

})

復制代碼

5.$.map()遍歷List/map

復制代碼
//遍歷List
var new_list = $.map(list2,function(items,index){
        return items+"!";
})
console.info(new_list);

//遍歷map
$.map(map_demo,function(key,value){
console.log(key
+":"+value);

});

復制代碼

小結:$.map()寫法和$.each()類似,但對list的遍歷時,參數順序和$.each()是相反的,並且可以帶返回值。對map的遍歷和$.each()一樣


————————————————
版權聲明:本文為CSDN博主「98年的香奈兒」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/soicant/article/details/79318181

https://www.cnblogs.com/xiaoliu66007/p/12880362.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM