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) })
时间: 2024-10-10 02:03:35