Array.prototype.forEach_ = function(fn,target=window) {
for(let i = 0; i<this.length;i++){
fn.call(target,this[i],i,this)
}
}
Array.prototype.map_ = function(fn,target=window) {
let res = []
for(let i = 0; i<this.length;i++){
res[i] = fn.call(target,this[i],i,this)
}
return res
}
Array.prototype.filter_ = function(fn){
let res = []
for (let i = 0; i < this.length; i++) {
if(fn(this[i])){
res.push(this[i])
}
}
return res
}
Array.prototype.every_ = function(fn,target=window){
let res = true
for (let i = 0; i < this.length; i++) {
if(!fn(this[i])){
res = false
}
}
return res
}
Array.prototype.some_ = function(fn,target=window){
let res = false
for (let i = 0; i < this.length; i++) {
if(fn(this[i])){
res = true
}
}
return res
}
Array.prototype.reduce_ = function(fn,...args){
let pre,start = 0
if(args.length!=0){
pre = args[0]
}else{
pre = this[0]
start = 1
}
for(let i = start ; i < this.length ; i++){
pre = fn(pre,this[i],i,this)
}
return pre
}
Array.prototype.findIndex_ = function(fn,target = window){
let res = -1
for(let i = 0 ; i<this.length;i++){
if(fn.call(target,this[i],i,this)){
res = i
}
}
return res
}
Array.prototype.find_ = function(fn,target = window){
let res = undefined
for(let i = 0 ; i<this.length;i++){
if(fn.call(target,this[i],i,this)){
res = this[i]
}
}
return res
}
Array.prototype.fill_ = function(val,start=0,end=this.length){
for(let i = start ; i<end;i++){
this[i] = val
}
}
Array.prototype.join_ = function(str=','){
let resStr = ''
for(let i = 0 ; i< this.length;i++){
const item = this[i]
resStr = i===0?item:`${resStr}${str}${item}`
}
return resStr
}
Array.prototype.flat_ = function(num=Infinity){
let arr = this,i=0
while(arr.some(item=>Array.isArray(item))){
arr = [].concat(...arr)
i++
if(i==num) break
}
return arr
}
JS手写——数组常见方法的手写(forEach、map、filter、every、some、reduce、find、findIndex、fill、join、flat)
最新推荐文章于 2024-04-11 11:45:52 发布