github:https://github.com/jingegebuguai/underscore-context
数组对象遍历(each)
each方法主要实现js的foreach函数:
目标:
var arr = [1, 2, 3]
arr.each((ele, index) => {
console.log(ele, index) //1,0 2,1 3,2
})
实现代码:
var _each = function(fn) {
if(typeof fn === 'function') {
var i, length = this.length
if(length === +length) {
for(i = 0; i < length; i++) {
fn.call(null, this[i], i, this)
}
} else {
var keys = Object.keys(this)
for(i = 0, length = keys.length; i < length; i++) {
fn.call(null, this[keys[i]], keys[i], this)
}
}
}
return this
}
Array.prototype.each = _each
Object.prototype.each = _each
var arr = {name: 'xxx', age: 18}
arr.each((ele, index) => {
console.log(ele, index)
})
Map API
实现对数组和对象的map操作
目标:
var arr = [1, 2, 3]
var newArr = arr.map((ele, index) =>{
return ele*2
})
console.log(newArr) //[2, 4, 6]
实现代码:
var newMap = function(fn) {
var keys = this.length !== +this.length && Object.keys(this)
var length = (keys || this).length, currentKey
var result = keys? {} : Array(length)
for(var i = 0; i < length; i++) {
currentKey = keys? keys[i] : i
result[currentKey] = fn.call(null, this[currentKey], currentKey, this)
}
return result
}
Array.prototype._map = newMap
Object.prototype._map = newMap
var arr1 = {name: 'xxx', age: '18'}
var arr2 = [1, 2, 3]
var obj = arr1._map((ele, index) => {
return ele*2
})
console.log(obj) //{ name: NaN, age: 36 }
Reduce API
实现对数组或对象的reduce操作
目标:
var arr = [1, 2, 3]
var sum = arr.reduce((prev, next) => {
return prev + next
})
console.log(newArr) //6
实现代码
var newReduce = function(fn, initValue) {
var keys = this.length !== +this.length && Object.keys(this)
var length = (keys || this).length, currentKey
var result, i = 0, key
if([].slice.call(arguments, 1) == undefined || arguments.length < 2) {
result = keys? this[keys[i++]] : this[i++]
} else {
result = initValue
}
for(; i < length; i++) {
key = keys? this[i] : i
result = fn.call(null, result, this[key], key, this)
}
return result
}
Array.prototype._reduce = newReduce
Object.prototype._reduce = newReduce
var arr1 = {name: 'xxx', age: '18'}
var arr2 = [1, 2, 3]
var sum = arr2._reduce((prev, next) => {
return prev + next
})
console.log(sum)
Filter API
实现对数组或对象的过滤操作
目标
var arr = [1, 2, 3, 4, 5, 6]
var result = arr.filter(ele => {
return ele % 2 == 0
})
console.log(result)
实现代码
var newFilter = function(fn) {
var length = this.length
var result = Object.prototype.toString.call(this) === '[object, Array]'? [] : {}
if(length === +length) {
for(var i = 0; i < length; i++) {
if(fn.call(null, this[i], i, this)) {
result.push(this[i])
}
}
} else {
var keys = Object.keys(this)
for(var i = 0; i < keys.length; i++) {
if(fn.call(null, this[keys[i]], keys[i], this)) {
result[keys[i]] = this[keys[i]]
}
}
}
return result
}