在使用 JavaScript 編寫代碼過程中,可以使用多個方法對數組進行遍歷;包括 for循環、forEach循環、map 循環、forIn循環和forOf循環等方法。
一、for 循環:基礎、簡單
這是最基礎和常用的遍歷數組的方法;各種開發語言一般都支持這種方法。
1
2
3
4
5
|
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() 方法:使用回調函數
forEach() 這是數組對象的一個方法;其接受一個回調函數為參數。
回調函數中有三個參數:
- 1st:數組元素(必選)
- 2nd:數組元素索引值(可選)
- 3rd:數組本身(可選)
1
2
3
4
5
6
|
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() 方法:使用回調函數
其使用方式和 forEach() 方法相同。
1
2
3
4
5
6
7
8
9
10
|
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 循環:遍歷對象和數組
for…in循環可用于循環對象和數組。
推薦用于循環對象,也可以用來遍歷json。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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 返回數組索引 console.log(arr[key]) // a b c d e } |
五、for…of 循環:遍歷對象和數組
可循環數組和對象,推薦用于遍歷數組。
for…of提供了三個新方法:
- key()是對鍵名的遍歷;
- value()是對鍵值的遍歷;
- entries()是對鍵值對的遍歷;
1
2
3
4
5
6
7
8
9
10
11
12
|
let arr = [ '科大訊飛' , '政法BG' , '前端開發' ]; for (let item of arr) { console.log(item); // 科大訊飛 政法BG 前端開發 } // 輸出數組索引 for (let item of arr.keys()) { console.log(item); // 0 1 2 } // 輸出內容和索引 for (let [item, val] of arr.entries()) { console.log(item + ':' + val); // 0:科大訊飛 1:政法BG 2:前端開發 } |
六、補充
6.1、break 和 Continue 問題
在 forEach、map、filter、reduce、every、some
函數中 break
和 continue
關鍵詞都會不生效,因為是在function中,但function解決了閉包陷阱的問題。
要想使用 break、continue 可以使用 for、for...in、for...of、while
。
6.2、數組和對象
用于遍歷數組元素使用:for(),forEach(),map(),for...of
。
用于循環對象屬性使用:for...in
。
以上就是JavaScript 數組遍歷的五種方法的詳細內容,更多關于JavaScript 數組遍歷的資料請關注服務器之家其它相關文章!
原文鏈接:https://cn-blogs.cn/archives/9583.html