for in 和 for of 相對于大家肯定都不陌生,都是用來遍歷屬性的, 首先看幾個例子.
遍歷對象:
const obj = {
a: 1,
b: 2,
c: 3
}
for (let i in obj) {
console.log(i) // //打印屬性:a,b,c
console.log(obj[i]); //打印屬性值1,2,3
}
for (let i of obj) {
console.log(i)
// Uncaught TypeError: obj is not iterable 報錯了
}
如果一定要用for of 遍歷對象,我們可以用Object.keys()
for(i of Object.keys(obj)){
console.log(i); // 打印屬性 a,b,c
console.log(obj[i]);// 打印屬性值1,2,3
}
以上代碼通過 for in 和 for of 對一個obj對象進(jìn)行遍歷,for in 正常的獲取了對象的 key值,分別打印 a、b、c,而 for of卻報錯了.
遍歷數(shù)組:
const arr = ['a', 'b', 'c']
// for in 循環(huán)
for (let i in arr) {
console.log(i)
// 0
// 1
// 2
}
// for of
for (let i of arr) {
console.log(i)
// a
// b
// c
}
以上代碼是對一個數(shù)組進(jìn)行遍歷, for in 返回的值為 0、1、2,這不是數(shù)組的下標(biāo)嗎? 而 for of 返回的是 a、b、c,這一次沒有報錯,為什么呢?
增加屬性:
const arr = ['a', 'b']
// 手動給 arr數(shù)組添加一個屬性
arr.name = 'qiqingfu'
// for in 循環(huán)可以遍歷出 name 這個鍵名
for (let i in arr) {
console.log(i)
// a
// b
// name
}
案例:
data:{
listParams:{
'光大':[
{ name:'光大---保通',brandUuid:'223' },
{name:'光大---華通', brandUuid:'123' }
],
'華貴':[
{ name:'華貴----陽光', brandUuid:'453' },
{ name:'華貴----復(fù)興', brandUuid:'678' },
{ name:'華貴----聯(lián)合', brandUuid:'670' }
]
}
}
如果后端返回的數(shù)據(jù)解構(gòu)是這種的,我們就可以用最簡單的for in 和for of 來獲取具體的值
created(){
for(var i in this.listParams){
console.log('object:>> ', this.listParams); // 整個listParams對象
for(var key of this.listParams[i]){
console.log('key :>> ', key.name); //每一個name值
}
}
}
for in 的特點(diǎn)
結(jié)合上面的兩個例子,分析得出:
1.for ... in 循環(huán)返回的值都是數(shù)據(jù)結(jié)構(gòu)的 鍵值名。
2.遍歷對象返回的對象的key值,遍歷數(shù)組返回的數(shù)組的下標(biāo)(key)。
3.for ... in 循環(huán)不僅可以遍歷數(shù)字鍵名,還會遍歷原型上的值和手動添加的其他鍵。
如——增加屬性的特別情況下, for ... in 循環(huán)會以任意的順序遍歷鍵名
總結(jié)一句: for in 循環(huán)特別適合遍歷對象。
for in遍歷數(shù)組得到的是數(shù)組的下標(biāo),for of遍歷數(shù)組得到的是數(shù)組的元素,for in遍歷鍵 , for of遍歷值
for of 特點(diǎn)
1.for of 循環(huán)用來獲取一對鍵值對中的值,而 for in 獲取的是 鍵名
2.一個數(shù)據(jù)結(jié)構(gòu)只要部署了 Symbol.iterator 屬性, 就被視為具有 iterator接口, 就可以使用 for of循環(huán).
3.第一題這個對象,沒有 Symbol.iterator這個屬性,所以使用 for of會報 obj is not iterable
4.for of 不同與 forEach, 它可以與 break、continue和return 配合使用,也就是說 for of 循環(huán)可以隨時退出循環(huán)。
5.提供了遍歷所有數(shù)據(jù)結(jié)構(gòu)的統(tǒng)一接口