在對數組或對象進行遍歷時,我們經常會使用到兩種方法: for in
和for of
,那么這兩種方法之間的區別是什么呢?讓我們來研究研究
簡單來說就是它們兩者都可以用於遍歷,不過for in
遍歷的是數組的索引(index
),而for of
遍歷的是數組元素值(value
)
// for in var obj = {a:1, b:2, c:3} for (let key in obj) { console.log(key) } // a b c //for of const array1 = ['a', 'b', 'c'] for (const val of array1) { console.log(val) } // a b c 復制代碼
先說說 for in
for in
更適合遍歷對象,當然也可以遍歷數組,但是會存在一些問題,
比如:
index
索引為字符串型數字,不能直接進行幾何運算
var arr = [1,2,3] for (let index in arr) { let res = index + 1 console.log(res) } //01 11 21 復制代碼
遍歷順序有可能不是按照實際數組的內部順序
使用for in
會遍歷數組所有的可枚舉屬性,包括原型,如果不想遍歷原型方法和屬性的話,可以在循環內部判斷一下,使用hasOwnProperty()
方法可以判斷某屬性是不是該對象的實例屬性
var arr = [1,2,3] Array.prototype.a = 123 for (let index in arr) { let res = arr[index] console.log(res) } //1 2 3 123 for(let index in arr) { if(arr.hasOwnProperty(index)){ let res = arr[index] console.log(res) } } // 1 2 3 復制代碼
再來說說ES6 中的 for of
for of
遍歷的是數組元素值,而且for of
遍歷的只是數組內的元素,不包括原型屬性和索引
var arr = [1,2,3] arr.a = 123 Array.prototype.a = 123 for (let value of arr) { console.log(value) } //1 2 3 復制代碼
for of
適用遍歷數/數組對象/字符串/map
/set
等擁有迭代器對象(iterator
)的集合,但是不能遍歷對象,因為沒有迭代器對象,但如果想遍歷對象的屬性,你可以用for in
循環(這也是它的本職工作)或用內建的Object.keys()
方法
var myObject={ a:1, b:2, c:3 } for (var key of Object.keys(myObject)) { console.log(key + ": " + myObject[key]); } //a:1 b:2 c:3 復制代碼
小結
for in
遍歷的是數組的索引(即鍵名),而for of
遍歷的是數組元素值
for in
總是得到對象的key
或數組、字符串的下標
for of
總是得到對象的value
或數組、字符串的值
了解更多前端培訓技術知識歡迎關注小編!