javaScript 數(shù)組操作

概要

  1. 實(shí)現(xiàn)一些常用的數(shù)組操作函數(shù)。

join

用法:[1, 2, 3].join('-') // "1-2-3"
實(shí)現(xiàn):

Array.prototype.join = function(char){
  let result = this[0] || ''
  for(let i=1; i<this.length; i++){
    result += char + this[i] 
  }
  return result
}

slice

用法:[1, 2, 3, 4].slice(1, 3) // [2, 3]
實(shí)現(xiàn):

Array.prototype.slice = function(startIndex, endIndex){
  console.log(1)
  let result = [],
      start = startIndex || 0,
      end = endIndex || this.length
  for(let i=start; i<end; i++){
    result.push(this[i])
  }
  return result
}

sort

用法:[1,2,3].sort( (a,b)=>{a-b} )
實(shí)現(xiàn):一般源代碼使用的是堆排序或是快速排序,這里使用復(fù)雜度較大的選擇排序

Array.prototype.sort = function(fn){
  let sortFn = fn || function(a,b){return a-b}
  for(let i=0; i<this.length-1; i++){
    for(let j=i+1; j<this.length; j++){
      if( sortFn.call(undefined, this[i], this[j]) < 0 ){
        [this[i], this[j]] = [this[j], this[i]]
      }
    }
  }
}

forEach

用法: 根據(jù)函數(shù)對(duì)每一項(xiàng)做相應(yīng)操作。
實(shí)現(xiàn):

Array.prototype.forEach = function(fn){
  for(let i=0; i<this.length; i++){
    if(i in this){
      fn.call(undefined, this[i], i, this)
    }
  }
}

forEach 與 for 的區(qū)別:

  1. forEach 不能 break。
  2. forEach 用到了函數(shù),所以每次迭代都會(huì)有一個(gè)新的函數(shù)作用域;而 for 循環(huán)只有一個(gè)作用域。

map

用法: 根據(jù)函數(shù)對(duì)每一項(xiàng)做相應(yīng)操作,并返回一個(gè)新的數(shù)組。
實(shí)現(xiàn):

Array.prototype.forEach = 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)
    }
  }
  return result
}

map 與 forEach 的區(qū)別:

  1. map 有返回值,所有 forEach 都可以用 map 來代替。

filter

用法:返回符合傳入函數(shù)返回值的項(xiàng)
實(shí)現(xiàn):

Array.prototype.forEach = function(fn){
  let result = [],
      temp
  for(let i=0; i<this.length; i++){
    if(i in this){
      if(temp = fn.call(undefined, this[i], i, this)){
        result.push(this[i])
      }
    }
  }
  return result
}

reduce

用法:將每一項(xiàng)通過函數(shù)作用與后一項(xiàng),返回一個(gè)結(jié)果
實(shí)現(xiàn):

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
}

map filter reduce 之間的聯(lián)系

  1. 用 reduce 表示 map
array2 = array.map( value => value + 1 )
可以寫作
array2 = array.reduce((result, value)=>{
  result.push(value + 1)
  return result
}, [])
  1. 用 reduce 表示 filter
array2 = array.filter( value => value % 2 === 0 )
可以寫作
array2 = array.reduce((result, value)=>{
  if( value % 2 === 0 ){
    result.push(value)
  }
  return result
}, [])
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容