GitHub 博客园 Nanakon

【Avalon源码】iterator

function iterator(vars, body, ret) {
    var fun = 'for(var ' + vars + 'i=0,n = this.length; i < n; i++){' +
            body.replace('_', '((i in this) && fn.call(scope,this[i],i,this))') +
            '}' + ret
    console.log(fun)
    return Function('fn,scope', fun)
}

Array.prototype.forEach = iterator('', '_', '')
Array.prototype.filter = iterator('r=[],j=0,', 'if(_)r[j++]=this[i]', 'return r')
Array.prototype.map = iterator('r=[],', 'r[i]=_', 'return r')
Array.prototype.some = iterator('', 'if(_)return true', 'return false')
Array.prototype.every = iterator('', 'if(!_)return false', 'return true')

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

 

posted on 2016-12-23 17:21  jzm17173  阅读(175)  评论(0编辑  收藏  举报

导航

轻音