关于前端:js-中for-of-和for-in-vue模板中-vforof-和vforin-变量数组和对象

4次阅读

共计 1557 个字符,预计需要花费 4 分钟才能阅读完成。

一. 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
正文完
 0