// for in遍歷的是數組的索引(即鍵名),而for of遍歷的是數組元素值。
let arr = [1,2,3,4,5,6,7]
for(let index of arr){
// console.log(index)//1 2 3 4 5 6 7
}
for(let index in arr){
// console.log(index)//0 1 2 3 4 5 6
//console.log(arr)//1 2 3 4 5 6 7
//console.log(arr[index])
}
//遍歷對象 通常用for in來遍歷對象的鍵名
let obj = {
a:1,
b:2,
c:3
}
for(let key in obj){
console.log(key)//a b c
//console.log(obj[key])//1 2 3
}
forEach
- 三個參數,第一個value, 第二個 index, 第三個數組體。
- 適用於 數組,set,map,不適應於 字符串,Object。
- 無法修改和刪除集合數據,效率和for循環相同,不用關心集合下標的返回。
- 不能終止循環,break,continue不能使用。
栗子:
let arr = [1, "ding", null, 5, true, undefined];
arr.forEach(function (value, index, a) {
console.log("value:", value, "index:", index, "a:", a);
})
for in
- 索引為字符串
- 多用於遍歷對象,json,數組,無順序,增加了轉換過程所以開銷比較大
- 可擴展屬性也會遍歷
- 支持break, continue
栗子:
for (let item in obj) {
console.log(item, ":", obj[item]);
if (item == "age") delete obj[item]; //刪除屬性成功
}
console.log("obj:", obj);
- 是目前遍歷數組最好的方法,可以用在set,map,類數組,字符串上,但是不支持原生的Object遍歷。
- 支持break, continue