封装一个既能遍历数组又能遍历对象的的forEach函数

javascript

浏览数:248

2019-1-8

AD:资源代下载服务
function newforEach(obj,fn) {
    var key;
    if(obj instanceof Array){
        obj.forEach(function(item,index){
            fn(item,index);
        })

    }else {
        for(key in obj){
            fn(key,obj[key]);
        }
    }
}var arr = [1,2,3];
newforEach(arr,function (item,index) {
    console.log(item);
});var obj = {
    x : 100,
    y :200
};

newforEach(obj,function (key,value) {
    console.log(key,value);
})