for(in/of)/forEarch的区别和使用

一、for in

  • 遍历数组
    输出索引
const arr = [
    {
        'name':1
    },{
        'name':2
    },{
        'name':3
    }
]
for(index in arr){
    console.log(index)
}
// 输出0  1  2
  • 遍历对象
    输出对象属性,包含原型链上的属性,可以使用hasOwnProperty方法过滤掉原型链上的属性
const obj = {
    'name':'张三',
    'age':20,
    'pro':'备注'
}
Object.prototype.protoName = '继承属性';
for(item in obj){
    console.log(item);// 输出name  age  pro protoName
    if(obj.hasOwnProperty(item)){
        console.log("自有属性: "+ item);// 输出name  age  pro 
    }
}

二、for of

  • 数组
    遍历出数组的每一项
const arr = [
    {
        'name':1
    },{
        'name':2
    },{
        'name':3
    }
]
for(item of arr){
    console.log(item)
}
// 输出{ name: 1 }
// { name: 2 }
// { name: 3 }
  • 对象
    for of不能遍历对象,因为对象原型上没有Symbol.iterator方法
    在这里插入图片描述
    为对象添加Symbol.iterator方法

const obj = {
    'name':'张三',
    'age':20,
    'pro':'备注'
}

Object.prototype[Symbol.iterator] = function() {
    let index = 0;
    let arr = Object.entries(this);
    let length = arr.length;
    return {
        next:()=>{
            if(index <= length){
                return {
                    value:arr[index++],
                    done:false
                }
            }else{
                return {
                    value:undefined,
                    done:true
                }
            }
        }
    }
}
for(item of obj){
    console.log(item);
}
// 输出
// [ 'name', '张三' ]
// [ 'age', 20 ]
// [ 'pro', '备注' ]
// undefined

三、forEach()

  • 数组
    接受三个参数,第一个为遍历的那一项,第二个是索引,第三个为数组本身
const arr = [
    {
        'name':1
    },{
        'name':2
    },{
        'name':3
    }
]

arr.forEach((item,index,arr) =>{
    console.log(item);
    console.log(index);
    console.log(arr);
    console.log('~~~~~~~~~~~~~~~~')
})
// 输出
// { name: 1 }
// 0
// [ { name: 1 }, { name: 2 }, { name: 3 } ]
// ~~~~~~~~~~~~~~~~
// { name: 2 }
// 1
// [ { name: 1 }, { name: 2 }, { name: 3 } ]
// ~~~~~~~~~~~~~~~~
// { name: 3 }
// 2
// [ { name: 1 }, { name: 2 }, { name: 3 } ]
// ~~~~~~~~~~~~~~~~
  • 对象
    对象不能直接使用forEach()遍历,可以用Object.keys()转换一下,转换出对象属性的一个数组能用foreach遍历访问的对象必须是集合或数组对象
const arr = [
    {
        'name':1
    },{
        'name':2
    },{
        'name':3
    }
]

const obj = {
    'name':'张三',
    'age':11,
    'demo':'22'
}

Object.keys(obj).forEach((item,index,arr) =>{
    console.log(item);
    console.log(index);
    console.log(arr);
    console.log('~~~~~~~~~~~~~~~~')
})
// 输出
// name
// 0
// [ 'name', 'age', 'demo' ]
// ~~~~~~~~~~~~~~~~
// age
// 1
// [ 'name', 'age', 'demo' ]
// ~~~~~~~~~~~~~~~~
// demo
// 2
// [ 'name', 'age', 'demo' ]
// ~~~~~~~~~~~~~~~~
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值