目錄
1. 普通for
循環
for
循環普通for循環可用於遍歷數組
let arr = ['A','B','C','D']
for(let i=0;i<arr.length;i++){
console.log(arr[i])
}
// A
// B
// C
// D
2. for(... in ...)
循環
for(... in ...)
循環可遍歷Array
,Object
對象
可以結合break
continue
return
, 隨時退出循環
遍歷返回的值都是數據結構的鍵名:
- 遍歷對象返回的對象的key值
- 遍歷數組返回的數組的下標(key)
const arr = ["A","B","C","D"]
for(let i in arr){
console.log(i)
// 0
// 1
// 2
// 3
}
const obj = {
a:1,
b:2,
c:3
}
for(let i in obj){
console.log(i)
// a
// b
// c
}
for(... in ...)
循環不僅可以遍歷數字鍵名,還會遍歷原型上的值和手動添加的其他鍵:
const arr = ["A","B","C"]
// 手動給arr數組添加一個屬性
arr.name='小白'
// for...in循環可以遍歷出name這個鍵名
for(let i in arr){
console.log(i)
// 0
// 1
// 2
// name
}
某些情況下,for…in
循環會以任意順序遍歷鍵名
const obj = {
100:'a',
1:'b',
20:'c'
}
for(let i in obj){
console.log(i)
// 1
// 20
// 100
}
主要是爲遍歷對象而設計的,不適用於遍歷數組
for...in
獲取的鍵名是字符串類型的
let arr = [1,2,3]
for (var index in arr) { // 千萬別這樣做
console.log(arr[index])
console.log(typeof index)
// 1
// string
// 2
// string
// 3
// string
}
由上,我們可以看出獲取的index,並不是數值類型,而是字符串類型。
如果我們在無意之間進行了字符串的計算:"1"+1=="21"
,๑乛◡乛๑bug就來嘍~
3. for(... of ...)
循環
for(... of ...)
循環- 可遍歷
iterable
可被迭代的對象(不包括Object)
一個數據結構只要部署了Symbol.iterator
屬性, 就被視爲具有iterator
接口, 就可以使用for ...of
循環
注意:
擁有iterator
接口的數據結構,有:
Array
(數組)Map
(映射)Set
(集合)String
(字符串)arguments對象
(傳遞給函數的參數的類數組對象)Nodelist對象
(獲取的dom列表集合)
凡是部署了iterator
接口的數據結構也都可以使用數組的擴展運算符(...)
、和解構賦值
等操作 - 只遍歷屬於對象本身的屬性
- 遍歷獲取的是鍵值
- 可以結合
break
continue
return
, 隨時退出循環
const arr = ["A","B","C","D"]
for(let i of arr){
console.log(i)
// A
// B
// C
// D
}
const obj = {
a:1,
b:2,
c:3
}
for(let i of obj){
console.log(i) // 報錯:obj is not iterable
}
for...of
遍歷對象需要通過和Object.keys()搭配使用
const obj = {
a: 1,
b: 2,
c: 3
}
console.log(Object.keys(obj)) // [ 'a', 'b', 'c' ]
for (let i of Object.keys(obj)) {
console.log(i)
// a
// b
// c
}
4. forEach
循環
forEach
循環可被迭代的對象有成員方法forEach()
只遍歷屬於對象本身的屬性
不能使用break
continue
return
arr.forEach(function(value,key,iterable){
console.log(key, value, iterable)
})
// 0 'A' [ 'A', 'B', 'C', 'D' ]
// 1 'B' [ 'A', 'B', 'C', 'D' ]
// 2 'C' [ 'A', 'B', 'C', 'D' ]
// 3 'D' [ 'A', 'B', 'C', 'D' ]
總結:
forEach
更多的用來遍歷數組,不能使用break
continue
return
退出循環for...in
一般用來遍歷對象或jsonfor...of
用來遍歷數組非常方便且比較安全for...in
循環出的是key,for...of
循環出的是value