本文实例讲述了js/jquery遍历对象和数组的方法。分享给大家供大家参考,具体如下:
JS forEach方法
arr[].forEach(function(value,index,array){ //do something })
var arr = [12,23,24,42,1]; var res = arr.forEach(function (item,index,input) { input[index] = item*10; }) console.log(res);//-->undefined; console.log(ary);//-->[120,230,240,420,10]; 通过数组索引改变了原数组
JS map方法
arr[].map(function(value,index,array){ //do something })
var arr = [12,23,24,42,1]; var res = arr.map(function (item,index,input) { return item*10; }) console.log(res);//-->[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改 console.log(ary);//-->[12,23,24,42,1]; 原数组并未发生变化
jQuery $.each方法
$.each(arr, function(index,value){ //do something })
var arr = [12,23,24,42,1]; $.each(arr, function (index,item) { console.log(index) // 0 1 2 3 4 console.log(item) // 12 23 24 42 1 })
PS:这里再为大家推荐一款JS数组遍历方式分析对比工具供大家参考:
在线JS常见遍历方式性能分析比较工具:http://tools.softyun.net/aideddesign/js_bianli
希望本文所述对大家JavaScript程序设计有所帮助。