JavaScript 數(shù)組遍歷的五種方法
在使用 JavaScript 編寫代碼過程中,可以使用多個(gè)方法對(duì)數(shù)組進(jìn)行遍歷;包括 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ù)組對(duì)象的一個(gè)方法;其接受一個(gè)回調(diào)函數(shù)為參數(shù)。回調(diào)函數(shù)中有三個(gè)參數(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):遍歷對(duì)象和數(shù)組
for…in循環(huán)可用于循環(huán)對(duì)象和數(shù)組。推薦用于循環(huán)對(duì)象,也可以用來遍歷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 返回?cái)?shù)組索引 console.log(arr[key]) // a b c d e}五、for…of 循環(huán):遍歷對(duì)象和數(shù)組
可循環(huán)數(shù)組和對(duì)象,推薦用于遍歷數(shù)組。
for…of提供了三個(gè)新方法:
key()是對(duì)鍵名的遍歷; value()是對(duì)鍵值的遍歷; entries()是對(duì)鍵值對(duì)的遍歷;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ā)}六、補(bǔ)充6.1、break 和 Continue 問題
在 forEach、map、filter、reduce、every、some 函數(shù)中 break 和 continue 關(guān)鍵詞都會(huì)不生效,因?yàn)槭窃趂unction中,但function解決了閉包陷阱的問題。要想使用 break、continue 可以使用 for、for...in、for...of、while。
6.2、數(shù)組和對(duì)象用于遍歷數(shù)組元素使用:for(),forEach(),map(),for...of 。用于循環(huán)對(duì)象屬性使用:for...in。
以上就是JavaScript 數(shù)組遍歷的五種方法的詳細(xì)內(nèi)容,更多關(guān)于JavaScript 數(shù)組遍歷的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python 如何在 Matplotlib 中繪制垂直線2. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼3. ASP常用日期格式化函數(shù) FormatDate()4. python中@contextmanager實(shí)例用法5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. 如何通過python實(shí)現(xiàn)IOU計(jì)算代碼實(shí)例9. 開發(fā)效率翻倍的Web API使用技巧10. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式
