一. js 中for ...of 和for ...in
1.数组循环
const test = ['a', 'b', 'c']for (const i of test) { console.log('item=', i)}后果是:取的数组元素item= aitem= bitem= cfor (const i in test) { console.log('item=', i)}后果是:取的是数组索引,并且值是string, 而非numitem= 0item= 1item= 2
2.对象循环
const A = { a: 1, b: 2, c: 4 }for (const i in A) { //in 读对象中的keys console.log('item=', i)}后果是: 获取的是keyitem= aitem= bitem= cfor (const i of A) { //报错, for...of不能遍历对象 console.log('item=', i)}for (const i of Object.keys(A)) { //先取key,失去数组 console.log('item=', i)}后果是item= aitem= bitem= cfor (const i of Object.values(A)) { //先取value,失去数组 console.log('item=', i)}后果是item= 1item= 2item= 3for (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&0bbbb&1cccc&2dddd&3aaaa&&0bbbb&&1cccc&&2dddd&&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*0ajja*value*1false*disabled*2已结案**label**0ajja**value**1false**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&02&13&2