在js中
var obj = {
q:'qqq',
w:'www',
e:'eee'
}
var arr1 = [
{r:'rrr'},
{t:'ttt'},
{y:'yyy'}
]
var arr2 = ['uuu','iii','ooo']
for(let i in obj){
console.log(i)//键名
}
for(let i in arr1){
console.log(i)//下标
}
for(let i in arr2){
console.log(i)//下标
}
for(let i of obj){
console.log(i)//报错,obj不是可迭代的
}
for(let i of arr1){
console.log(i)//值 {r:'rrr'}...
}
for(let i of arr2){
console.log(i)//值 uuu...
}
小结:for(let i in arr/obj)遍历数组时遍历的是下标,遍历对象时遍历的是键名。for(let i of arr)遍历数组时遍历的是值,遍历对象会报错(不可迭代)。
在vue中v-for指令
new Vue({
el: '#box',
data: {
posts1: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
],
posts2: ['qq','ww','ee'],
posts3: {
name1:'rr',
name2:'tt',
name3:'yy'
}
}
})
<div id='box'>
<div v-for="(post,i) in posts1" :key="post.id">{{post}}-{{i}}</div>
<div v-for="(post,i) of posts1" :key="post.id">{{post}}-{{i}}</div><br/>
<div v-for="(post,i) in posts2" :key="post.i">{{post}}--{{i}}</div>
<div v-for="(post,i) of posts2" :key="post.i">{{post}}--{{i}}</div><br/>
<div v-for="(post,i,j) in posts3" :key="post.j">{{post}}-{{i}}-{{j}}</div>
<div v-for="(post,i,j) of posts3" :key="post.j">{{post}}-{{i}}-{{j}}</div>
</div>
小结:posts无论是数组,对象或者对象数组,无论是 in/of 遍历的永远是值。如果是数组,若想遍历下标可以用v-for=’(i,j) in/of posts’,其中 i 是值 j 是下标;如果是对象,若想遍历下标和键名可以用v-for=’(i,j,n) in/of posts’,其中 i 是值 j 是键名 n 是下标。
可能有错误,还请指正!