forEach
forEach專門用來循環數組,可以直接取到元素,同時也可以取到index值
存在局限性,不能continue跳過或者break終止循環,沒有返回值,不能return
let arr = ['a', 'b', 'c', 'd'] arr.forEach(function (val, index, arr) { console.log('index:'+index+','+'val:'+val) // val是當前元素,index當前元素索引,arr數組 console.log(arr) }) //index:0,val:a //["a", "b", "c", "d"]0: "a"1: "b"2: "c"3: "d" //index:1,val:b //["a", "b", "c", "d"] //index:2,val:c //["a", "b", "c", "d"] //index:3,val:d //["a", "b", "c", "d"]
for in
for...in 一般循環遍歷的都是對象的屬性,遍歷對象本身的所有可枚舉屬性,以及對象從其構造函數原型中繼承的屬性
key會變成字符串類型
let arr = [1,2,3,4]; arr.b='100'; for(let key in arr){ console.log(key);//會把b輸出來 }
//遍歷數組時,item表示索引值, arr表示當前索引值對應的元素 arr[item] var arr = ['a','b','c']; for (var item in arr) { console.log(item) //0 1 2 console.log(arr[item]) //a b c } //遍歷對象時,item表示key值,arr表示key值對應的value值 obj[item] var obj = {a:1, b:2, c:3}; for (let item in obj) { console.log("obj." + item + " = " + obj[item]); } // obj.a = 1 // obj.b = 2 // obj.c = 3
for of
for of是ES6新引入的特性。修復了ES5中for in的不足
允許遍歷 Arrays(數組)、Strings(字符串)、Maps(映射)、Sets(集合)等可迭代的數據結構
for of 支持return, 只能遍歷數組不能遍歷對象(遍歷對象需要通過和Object.keys()搭配使用)
/*循環一個數組*/ let arr = ['A', 'B', 'C'] for (let val of arr) { console.log(val) } // A B C /*循環一個字符串:*/ let iterable = "abc"; for (let value of iterable) { console.log(value); } // "a" // "b" // "c" /*循環一個擁有enumerable屬性的對象*/ for (var key of Object.keys(someObject)) { console.log(key + ": " + someObject[key]); } //for of 並不能直接使用在普通的對象上,需要通過和Object.keys()搭配使用
總結:
forEach更多的用來遍歷數組
for in 一般常用來遍歷對象或json
for of 用來遍歷數組非常方便且比較安全
for in循環出的是key,for of循環出的是value