JavaScript 數(shù)組遍歷的五種方法
在使用 JavaScript 編寫代碼過程中,可以使用多個方法對數(shù)組進行遍歷;包括 for循環(huán)、forEach循環(huán)、map 循環(huán)、forIn循環(huán)和forOf循環(huán)等方法。
一、for 循環(huán):基礎(chǔ)、簡單這是最基礎(chǔ)和常用的遍歷數(shù)組的方法;各種開發(fā)語言一般都支持這種方法。
let arr = [’a’,’b’,’c’,’d’,’e’];for (let i = 0, len = arr.length; i < len; i++) { console.log(i); // 0 1 2 3 4 console.log(arr[i]); //a b c d e}二、forEach() 方法:使用回調(diào)函數(shù)
forEach() 這是數(shù)組對象的一個方法;其接受一個回調(diào)函數(shù)為參數(shù)。回調(diào)函數(shù)中有三個參數(shù):
1st:數(shù)組元素(必選) 2nd:數(shù)組元素索引值(可選) 3rd:數(shù)組本身(可選)let arr = [’a’,’b’,’c’,’d’,’e’];arr.forEach((item,index,arr)=> { console.log(item); // a b c d e console.log(index); // 0 1 2 3 4 console.log(arr); // [’a’,’b’,’c’,’d’,’e’]})三、map() 方法:使用回調(diào)函數(shù)
其使用方式和 forEach() 方法相同。
var arr = [ {name:’a’,age:’18’}, {name:’b’,age:’19’}, {name:’c’,age:’20’}];arr.map(function(item,index) { if(item.name == ’b’) { console.log(index) // 1 }})四、for..in 循環(huán):遍歷對象和數(shù)組
for…in循環(huán)可用于循環(huán)對象和數(shù)組。推薦用于循環(huán)對象,也可以用來遍歷json。
let obj = { name: ’王大錘’, age: ’18’, weight: ’70kg’}for(var key in obj) { console.log(key); // name age weight console.log(obj[key]); // 王大錘 18 70kg}----------------------------let arr = [’a’,’b’,’c’,’d’,’e’];for(var key in arr) { console.log(key); // 0 1 2 3 4 返回數(shù)組索引 console.log(arr[key]) // a b c d e}五、for…of 循環(huán):遍歷對象和數(shù)組
可循環(huán)數(shù)組和對象,推薦用于遍歷數(shù)組。
for…of提供了三個新方法:
key()是對鍵名的遍歷; value()是對鍵值的遍歷; entries()是對鍵值對的遍歷;let arr = [’科大訊飛’, ’政法BG’, ’前端開發(fā)’];for (let item of arr) { console.log(item); // 科大訊飛 政法BG 前端開發(fā)}// 輸出數(shù)組索引for (let item of arr.keys()) { console.log(item); // 0 1 2}// 輸出內(nèi)容和索引for (let [item, val] of arr.entries()) { console.log(item + ’:’ + val); // 0:科大訊飛 1:政法BG 2:前端開發(fā)}六、補充6.1、break 和 Continue 問題
在 forEach、map、filter、reduce、every、some 函數(shù)中 break 和 continue 關(guān)鍵詞都會不生效,因為是在function中,但function解決了閉包陷阱的問題。要想使用 break、continue 可以使用 for、for...in、for...of、while。
6.2、數(shù)組和對象用于遍歷數(shù)組元素使用:for(),forEach(),map(),for...of 。用于循環(huán)對象屬性使用:for...in。
以上就是JavaScript 數(shù)組遍歷的五種方法的詳細內(nèi)容,更多關(guān)于JavaScript 數(shù)組遍歷的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 關(guān)于WPF WriteableBitmap類直接操作像素點的問題2. JavaScript前端中的偽類元素before和after使用詳解3. ASP基礎(chǔ)入門第一篇(ASP技術(shù)簡介)4. asp取整數(shù)mod 有小數(shù)的就自動加15. 源碼分析MinimalApi是如何在Swagger中展示6. PHP laravel實現(xiàn)基本路由配置詳解7. ThinkPHP5實現(xiàn)JWT Token認證的過程(親測可用)8. 熊海CMS代碼審計漏洞分析9. PHP JSAPI調(diào)支付API實現(xiàn)微信支付功能詳解10. 表單中Readonly和Disabled的區(qū)別詳解
