一. js 中for ...of 和for ...in

1.数组循环

const test = ['a', 'b', 'c']
for (const i of test) {
  console.log('item=', i)
}
结果是:取的数组元素
item= a
item= b
item= c


for (const i in test) {
  console.log('item=', i)
}
结果是:取的是数组索引,并且值是string, 而非num
item= 0
item= 1
item= 2

2.对象循环

const A = { a: 1, b: 2, c: 4 }
for (const i in A) { //in  读对象中的keys
  console.log('item=', i)
}
结果是: 获取的是key
item= a
item= b
item= c

for (const i of A) { //报错, for...of不能遍历对象
  console.log('item=', i)
}

for (const i of Object.keys(A)) { //先取key,得到数组
  console.log('item=', i)
}
结果是
item= a
item= b
item= c

for (const i of Object.values(A)) { //先取value,得到数组
  console.log('item=', i)
}
结果是
item= 1
item= 2
item= 3



for (const i of Object.entries(A)) {// key val 组成数组
  console.log('item=', i)
}
结果是
item= ['a', 1]
item= ['b', 2]
item= ['c', 3]

总结,对数组而言:for...of 循环的是数组内的元素内容, 而使用for...in 循环的是数组索引下标。

对对象而言: 直接使用for...of循环对象会报错, 但可以取对象的所有keys或所有values 进行遍历; for...in 循环的是对象的key

二。在vue 模板中使用 v-for...of 和v-for...in, 循环数组或对象,

1.遍历数组

//arr1: ['aaaa', 'bbbb', 'cccc', 'dddd'],
<p v-for="(item, index) in arr1" :key="index + 'test1'">
      {{ item + '&&' + index }}
    </p>

    <p v-for="(key, val, index) of obj1" :key="index + 'testt0'">
      {{ key + '*' + val + '*' + index }}
    </p>

// 结果是
aaaa&0
bbbb&1
cccc&2
dddd&3

aaaa&&0
bbbb&&1
cccc&&2
dddd&&3

2.遍历对象

//obj1: { label: '已结案', value: 'ajja', disabled: false }
<p v-for="(key, val, index) of obj1" :key="index + 'testt0'">
      {{ key + '*' + val + '*' + index }}
    </p>

    <p v-for="(key, val, index) of obj1" :key="index + 'testt1'">
      {{ key + '**' + val + '**' + index }}
    </p>

结果是:
已结案*label*0
ajja*value*1
false*disabled*2

已结案**label**0
ajja**value**1
false**disabled**2

总结: 显示上并没有什么区别, 但建议,最好使用v-for...of 遍历数组, 使用v-for...in 遍历对象

附加
可以直接循环一个数值, 则从1开始累加循环到该数值 v-for="i in 25" 结果的是1-25

<p v-for="(item, index) of 3" :key="index + 'test0'">
      {{ item + '&' + index }}
    </p>

//结果是:
1&0
2&1
3&2

CUI_PING
42 声望3 粉丝