遍历对象和数组的forEach函数

遍历数组使用forEach,而遍历对象使用for in,但是在实际开发中,可以使用一个函数就遍历两者,jquery 就有这样的函数

function forEach(obj, fn) {
    var key
    if (obj instanceof Array) {
        // 准确判断是不是数组
        obj.forEach(function (item, index) {
            fn(index, item)
        })
    } else {
        // 不是数组就是对象
        for (key in obj) {
            fn(key, obj[key])
        }
    }
}

var arr = [1,2,3]
// 注意,这里参数的顺序换了,为了和对象的遍历格式一致
forEach(arr, function (index, item) {
    console.log(index, item)
})

var obj = {x: 100, y: 200}
forEach(obj, function (key, value) {
    console.log(key, value)
})

猜你喜欢

转载自www.cnblogs.com/mushitianya/p/10656938.html
今日推荐