for...in 和for...of 遍历数组、对象和字符串时的区别

一、遍历数组

使用for…in 会遍历数组元素下标
let items = ['alex', 18,'boy']
for(let item in items){
	console.log(item) //数组元素下标
}

在这里插入图片描述
可通过数组元素下标获取对应元素

for(let item in items){
	console.log(item+":"+items[item]) 
}

在这里插入图片描述

使用for…of 可遍历数组元素
for(let item of items){
	console.log(item)
}

在这里插入图片描述

二、遍历对象

使用for…in 会遍历对象属性名
let obj = {name:'alex',age : 18,sex : 'boy'}
for(let item in obj){
	console.log(item) //对象属性名
}

在这里插入图片描述
可通过对象属性名获取对应的属性值

for(let item in obj){
	console.log(item+":"+obj[item]) 
}

在这里插入图片描述

使用for…of 会报错
for(let item of obj){
	console.log(item)
}

在这里插入图片描述

三、遍历字符串

使用for…in 会遍历字符串中字符下标
let str = '23123';
for(item in str){
	console.log(item) //字符串中字符下标
}

在这里插入图片描述

使用for…of 可遍历字符串中字符
for(item of str){
	console.log(item) //字符串中字符
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值