写一个能遍历数组和对象的forEach函数


forEach函数遍历数组:

var arr = [1,2,3];
arr.forEach (function (item, index) {
    console.log (index,item)
})

forEach函数遍历对象:

var obj = {
    x: 100,
    y: 200,
    z: 300
}
var key;
for (key in obj){
    if (obj.hasOwnProperty (key)) {
        console.log (key,obj[key])
    }
}

能遍历二者的forEach函数

function forEach (obj, fn) {
    var key;
    if (obj instanceof Array) {
        obj.forEach (function (item, index) {
            fn (item,index)
        })
    } else {
        for (key in obj) {
            if (obj.hasOwnProperty (key)){
                fn (key, obj[key])
            }
        }
    }
}
var arr = [1, 2, 3];
var obj = {
    x: 100,
    y: 200,
    z: 300
}
forEach (arr, function (item, index) {
    console.log (index,item)
})
forEach (obj, function (key, val) {
    console.log (key, val)
})

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM