js中常用的遍历方法

js中常用的遍历方法

记录一下js中常见的遍历方法,以免突然想不起

常见的需要遍历的目标

// 数组
var a = [ 1, 2, 3 ];
// 数组含对象
var b = [ {a:1}, {b:2}, {c:3} ];
// 纯对象
var obj = { a:1, b:2, c:3 };

1、for(let ; ; ) 最常见的用法
这个用法可以解决大部分遍历问题

for(let i = 0 ; i < a.length; i++  ){
	console.log(a[i]); // 1,2,3
}

2、for( let … in … ) 只有这个才能直接遍历对象
遍历hash数组,或者类数组对象
也可以遍历数组,但意义不大

for(let key in obj){
	console.log(key); // a,b,b
	console.log(obj[key]); // 1,2,3
}

3、forEach() 遍历
(我有同事跟我说这是es6语法,但是其实不是,但我确实用的不多)

b.forEach((item, index)=>{
	console.log(item); // {a:1},{b:2},{c:3}
	console.log(index); // 0, 1, 2
})

/es6语法/
// 4、 for(let … of … ) 对象无法直接遍历

// 例子1 数组
for(let item of a){
	console.log(item); // 1,2,3
}
	
// 例子2 数组含对象
for(let item of b){
	console.log(item); // {a:1},{b:2},{c:3}
}

// 例子3 数组含对象 遍历出value
for(let item of b.values() ){
	console.log(item); // {a:1},{b:2},{c:3}
}

// 例子4 数组含对象 遍历出key
for(let index of b.keys() ){
	console.log(index); // 0,1,2
}

// 例子5 数组含对象 遍历出value和index

for(let [item, index] of b.entries() ){
	console.log(item); // {a:1},{b:2},{c:3}
	console.log(index); // 0,1,2
}

没了

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值