JavaScript里的for in与 for of

  1. for …in 遍历 键名;遍历对象的整个原型链,性能差
    数组不太适用!
// 遍历对象    i 是 key, a 是 对象本身
let a = {name: 'zs', age: 18, sex: 'man'};
for(let i in a) {
	console.log(i + '---' + a[i])
} // name---zs age---18 sex---man

// 遍历数组  不建议不建议不建议
let a = [1, 3, 5, 7, 9];
for(let i in a) {
	console.log(i + '---' + a[i])
}// 0---1 1---3 2---5...
  1. for…of ES6的语法;遍历 键值;只遍历对象本身
    对象不太适用!!!!!
// 遍历数组  
let a = [1, 3, 5, 7, 9];
for(let i of a) {
	console.log(i)
}// 1 3 5 7 9

// 遍历字符串  
let a = 'qwer';
for(let i of a) {
	console.log(i)
}// q w e r

// 也可以遍历 Set类型数据
let a = [1, 3, 5, 7, 9];
let b = new Set(a);
for(let i of b) {
	console.log(i, b)
}// 1 3 5 7 9 

总结就是: for…in适合遍历对象; for…of适合遍历数组(类数组)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值