与我们合作
我们专注:网站策划设计、网络多媒体传播、网站优化及网站营销、品牌策略与设计
主营业务:网站建设、移动端微信小程序开发、VI设计、网络运营、云产品·运维解决方案
有一个品牌项目想和我们谈谈吗?
您可以填写右边的表格,让我们了解您的项目需求,这是一个良好的开始,我们将会尽快与您取得联系。当然也欢迎您给我们写信或是打电话,让我们听到您的声音
您也可通过下列途径与我们取得联系:
地 址: 深圳.龙岗区大运软件小镇11栋3楼
电 话: 138 2888 4598 / 138 0880 9053
网 址: http://www.appvx.cn
快速提交您的需求 ↓
javascript如何遍历list?下面本篇文章给大家介绍一下JS中对List、Map的各种遍历方式。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
1.最常用的for循环
for(var i=0;i<list2.length;i++){
console.info(i +":"+ list2 [i]);
}
改进:这里可以将list2.length提出来,不用每次计算长度,效率更高一些,such as:
var len=list2.length;
for(var i=0;i<len;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()一样。