js中for(const i in/of arr/obj)和vue中v-for指令的区别

在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 是下标。

可能有错误,还请指正!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值