注:for...of是ES6新引入的特性碎节。修復(fù)了ES5引入的for...in的不足
先定義一個(gè)數(shù)組:let aArray = ['a', 123, { a: '1', b: '2' }];
for...in
循環(huán):
for (let index in aArray) {
console.log(aArray[index]); // a 123 {a: "1", b: "2"}
}
for...of
循環(huán):
for (var value of aArray) {
console.log(value); // a 123 {a: "1", b: "2"}
}
這里結(jié)果一樣,for...in
循環(huán)出的是key麻敌,for...of
循環(huán)出的是value
假設(shè)我們往數(shù)組中添加一個(gè)屬性aArray.name = 'hi'
,再看兩個(gè)循環(huán)的結(jié)果:
for (let index in aArray) {
console.log(aArray[index]); // a 123 {a: "1", b: "2"} hi
}
for (var value of aArray) {
console.log(value); // a 123 {a: "1", b: "2"}
}
得出結(jié)論:作用于數(shù)組的for-in
循環(huán)除了遍歷數(shù)組元素以外,還會(huì)遍歷自定義屬性。
for...of
循環(huán)不會(huì)循環(huán)對(duì)象的key,只會(huì)循環(huán)出數(shù)組的value亭珍,因此for...of
不能循環(huán)遍歷普通對(duì)象,對(duì)普通對(duì)象的屬性遍歷推薦使用for...in
循環(huán)一個(gè)對(duì)象試一下:
var student = {
name: 'wujunchuan',
age: 22,
locate: {
country: 'china',
city: 'xiamen',
school: 'XMUT'
}
}
for (let index in student) {
console.log(student[index]); // wujunchuan 22 {country: "china", city: "xiamen", school: "XMUT"}
}
for (var value of student) {
console.log(value); // student is not iterable
}
因此for...of
不能循環(huán)遍歷普通對(duì)象
總結(jié):
1.for...in
循環(huán)出的是key值,for...of
循環(huán)出的是value值
2.推薦在循環(huán)對(duì)象屬性的時(shí)候枝哄,使用for...in
,在遍歷數(shù)組的時(shí)候的時(shí)候使用for...of
3.for...of
不能循環(huán)普通的對(duì)象肄梨,需要通過和Object.keys()
搭配使用