JS 几种常见的遍历方式

在这里插入图片描述

JS 几种常见的遍历方式

for循环

  • 普通的写法
    let arr = [1,2,3];
    for(let i =0;i<arr.length;i++){
    console.log(arr[i])    // 1 2 3
    }
    
  • 改进的写法

    因为每次arr.length都会重复获取数组的长度,因此会导致性能的损失
    所以我们可以先使用一个变量将其缓存起来,从而达到性能的优化

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

for in 循环

  • 用于遍历数组或者对象的属性
    const obj = { 
    	a: 1, 
    	b: 2, 
    	c: 3 
    } 
    for(let i in obj){
       console.log(i,obj[i]); // a 1  b 2  c 3
    }
    

for of 循环

  • 用于遍历数组,不能用于遍历对象,否则会报错
  1. 遍历对象
    const obj = { 
    	a: 1, 
    	b: 2, 
    	c: 3 
    } 
    for(let i of obj){
    	  console.log(i,obj[i]); // TypeError: obj is not iterable
    }
    
  2. 遍历数组
    let arr = [11,22,33];
    for(let i of arr){
    	console.log(i); // 11  22  33
    }
    

forEach循环

  • 用于遍历数组中的值

    使用forEach时,要使用一个function回调函数。

    let arr = [1,2,3];
    arr.forEach(function(i){
        console.log(i);// 1 2 3
    })
    

map方法

  • 不改变原数组,返回回调函数里的结果
    let arr = [1,2,3];
    arr.map(function(i){
        console.log(i);// 1 2 3
    })
    

参考资料

链接: https://juejin.cn/post/7087506699057135653

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值