寫一個能遍歷數組和對象的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