map()
Array.prototype.myMap = function (callback) {
const arr = []
for (let index = 0; index < this.length; index++) {
const element = this[index];
const result = callback(element, index)
arr.push(result)
}
return arr
}
const arr = [55,22,11,33,44]
const res = arr.myMap((item,index) => item + 10)
console.log(res)
reduce()
Array.prototype.myReduce = function (callback, initValue) {
let total = initValue
for (let index = 0; index < this.length; index++) {
const element = this[index];
total = callback(total, element, index)
}
return total
}
const arr = [55,22,11,33,44]
const res = arr.myReduce((pre,item) => pre *= item)
console.log(res)
filter()
Array.prototype.myFilter = function (callback) {
const arr = []
for (let index = 0; index < this.length; index++) {
const element = this[index];
const result = callback(element, index)
if (result) {
arr.push(element)
}
}
return arr
}
const arr = [55,22,11,33,44]
const resArr = arr.myFilter((item,index)=>{
console.log(item,index)
return item > 2
})
console.log(res)
find()
Array.prototype.myFind = function(callback) {
if(typeof callback !== 'function') {
throw 'argument must be a function'
}
for(let i = 0; i < this.length; i++) {
const element = this[i]
const result = callback(element,i)
if(result) return element
}
return undefined
}
const arr = [55,22,11,33,44]
const res = arr.myFind((item,index)=> item===3)
console.log(res)
findIndex()
Array.prototype.myFindIndex = function(callback) {
if(typeof callback !== 'function') {
throw 'argument must be a function'
}
for(let i = 0; i < this.length; i++) {
const element = this[i]
const result = callback(element,i)
if(result) return i
}
return -1
}
const arr = [55,22,11,33,44]
let res = arr.myFindIndex((item,index)=> item===3)
console.log(res)
every()
Array.prototype.myEvery = function(callback) {
if(typeof callback !== 'function') {
throw 'argument must be a function'
}
for(let i = 0; i < this.length; i++) {
const element = this[i]
const result = callback(element,i)
if(!result) return false
}
return true
}
const arr = [55,22,11,33,44]
const res = arr.myEvery((item,index)=>{
return item > 0
})
console.log(res)
some()
Array.prototype.mySome = function(callback) {
if(typeof callback !== 'function') {
throw 'argument must be a function'
}
for(let i = 0; i < this.length; i++) {
const element = this[i]
const result = callback(element,i)
if(result) return true
}
return false
}
const arr = [55,22,11,33,44]
const res = arr.mySome((item,index)=>{
return item = 2
})
console.log(res)
forEach()
Array.prototype.myForEach = function(callback) {
if(typeof callback !== 'function') {
throw 'argument must be a function'
}
for(let i = 0; i < this.length; i++) {
const element = this[i]
callback(element,i)
}
}
const arr = [55,22,11,33,44]
arr.myForEach((item,index)=>{
console.log(item,index)
})
console.log(res)