let arrSome = [12,15,19]
Array.prototype.mySome = function(fn) { //必須使用function不能使用箭頭函數,this指向調用的數組
if(typeof fn != 'function'){
throw new TypeError(`error ${fn} no a function `)
}
for (let i = 0; i < this.length; i++) {
if(fn(this[i])){
return true
}
}
return false
}
let some = arrSome.mySome(item => {
return item > 19
})
console.log('some:'+some) // some:false
4. 模擬實現every
let arrEvery = [12,15,19]
Array.prototype.myEvery = function(fn) {
if(typeof fn != 'function'){
throw new TypeError(`error ${fn} no a function `)
}
for (let i = 0; i < this.length; i++) {
if(!fn(this[i])){
return false
}
}
return true
}
let every = arrEvery.myEvery(item => {
return item > 19
})
console.log('every:'+every) // every:false
5. 模擬實現map
let arrMap = [12,15,19]
Array.prototype.myMap = function(fn) { //必須使用function不能使用箭頭函數,this指向調用的數組
if(typeof fn != 'function'){
throw new TypeError(`error ${fn} no a function `)
}
let arrayData = []
for (let i = 0; i < this.length; i++) {
if(fn(this[i])){
arrayData.push(fn(this[i]))
}
}
return arrayData;
}
let map = arrMap.map(item => {
item += 3;
return item + 'map'
})
console.log('map:'+map) // map:15map,18map,22map
6. 模擬實現filter
let arrFilter = [12,15,19]
Array.prototype.myFilter = function(fn) { //必須使用function不能使用箭頭函數,this指向調用的數組
if(typeof fn != 'function'){
throw new TypeError(`error ${fn} no a function `)
}
let arrayData = []
for (let i = 0; i < this.length; i++) {
if(fn(this[i])){
arrayData.push(this[i])
}
}
return arrayData;
}
let filter = arrFilter.myFilter(item => {
return item > 12
})
console.log('filter:'+filter) // filter:15,19
7. 模擬實現reduce
let arrReduce = [12,15,19]
Array.prototype.myReduce = function(fn,obj) { //必須使用function不能使用箭頭函數,this指向調用的數組
if(typeof fn != 'function'){
throw new TypeError(`error ${fn} no a function `)
}
for (let i = 0; i < this.length; i++) {
obj = fn(obj,this[i])
}
return obj
}
let reduce = arrReduce.myReduce((pre,item) => {
pre = pre + item
return pre
},0)
console.log('reduce:'+reduce) // reduce:46