本文實例講述了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 })
參考:
https://www.gxlcms.com/article/81955.htm
https://www.gxlcms.com/article/84609.htm
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼運行效果。
PS:這里再為大家推薦一款JS數組遍歷方式分析對比工具供大家參考:
在線JS常見遍歷方式性能分析比較工具:http://tools.jb51.net/aideddesign/js_bianli
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數組操作技巧總結》、《JavaScript遍歷算法與技巧總結》、《javascript面向對象入門教程》、《JavaScript數學運算用法總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript錯誤與調試技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com