Array API
//join
Array.prototype.join = function(char){
let result = this[0] || ''
let length = this.length
for(let i=0;i<length;i++){
result += char + this[i]
}
return result
}
//slice
Array.prototype.slice = function(begin,end){
let result = this[0] || ''
begin = begin || 0
end = end || thsi.length
for(let i = begin;i<end;i++){
result.push(this[i])
}
return result
}
//sort
Array.prototype.sort = function(fn){
fn = fn || (a,b)=>a-b
let roundCount = this.length -1
for(let i=0;i<roundCount;i++){
for(let k=i+1;k<this.length;k++){
if(fn.call(null,this[k],this[i])<0){
[this[i],this[k]] = [this[k],this[i]]
}
}
}
}
//forEach
Array.prototype.forEach = function(fn){
for(let i=0;i<this.length;i++){
if(i in this){
fn.call(undefined,this[i],i this)
}
}
}
//map
Array.prototype.map = function(fn){
let result = []
for(let i=0;i<this.length;i++){
if(i in this){
result[i] = fn.call(undefined,this[i],i this)
}
}
rturn result
}
//filter
Array.prototype.filter = function(fn){
let result = []
for(let i=0;i<this.length;i++){
if(i in this){
if(fn.call(undefined,this[i],i,this)){
result.push(this[i])
}
}
}
return result
}
//reduce
Array.prototype.reduce = function(fn,init){
let result = init
for(let i=0;i<this.length;i++){
if(i in this){
result = fn.call(undefined,result,this[i],i,this)
}
}
return result
}
array2 = array.map(v => v+1)
array2 = array.reduce((result,v)=>{
result.push(v+1)
return result
},[])
array2 = array.filter(v => v%2 === 0)
array3 = array.reduce((result,v)=>{
if(v%2 === 0){
result.push(v)
}
return result
},[])
函数节流
多长时间内 只执行一次
技能有cd 如果你一秒内用了一次 那你只能一秒后再用
fn2 = throttle(fn,time){
let cd = false
return function(){
if(cd) {return}
fn.call()
cd = true
setTimeout(()={cd = false},time)
}
}
函数防抖
等多长时间不说话 我就去行动
我不想那么快的去做这件事情 我希望你把话说完了我再去做
我不想用户每次滚动都要去做这件事情 我希望用户停下来了 我再去做这件事情
我不想用户每次输入一个汉字我都要去问后台 我等用户停止输入了 我再去
debounce = function(fn,time){
let timer = undefined
return function(){
if(timer !== undefined){
window.clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.call()
},time)
}
}
fn = function(){
console.log(1)
}
fn2 = debounce(fn,10000)
网友评论