Js 常用方法及問題匯總

數(shù)組扁平化

  • 常規(guī)方法:
    var arr = [1,[2,3]]
    var arr2 = [1,2,[3,[4,5]]]
    arr.flat(1) // [1,2,3]
    arr2.flat(2) // [1,2,3,4,5]
    
  • 騷方法:
    arr1.toString().split()
    arr2.toString().split(',')
    或者
    arr1.join(',').split(',')
    

類型判斷

  • typeof:
    typeof 1 // number
    tyupeof '' // string
    typeof Symbol() // symbol
    typeof undefined // undefined
    typeof Object // function
    typeof null // object ---shit!
    typeof [] // object
    typeof new Date() // object
    

可以看出typeof只能簡單的判斷出基本類型,并且null還有坑

  • instanceof

    a instanceof b, 
    原理是a.__proto__...__proto__ 與 b.prototype 比較是否相等,通俗的來講就是能否通過a的原型鏈找到b的原型。(由此就會(huì)造成誤解 [] instanceof Object // true)
    
  • Object.prototype.toString.call()

    幾乎完美的判斷出類型
    Object.prototype.toString.call(1) // [object Number]
    Object.prototype.toString.call('') // [object String]
    Object.prototype.toString.call(null) // [object Null]
    ...
    

    但是據(jù)說ie6下有問題, string,null,undefined會(huì)誤判斷為object(未考證!)

遞歸爆棧問題

function f(n) {
  if (n === 0 || n === 1) return n 
  else return f(n - 1) + f(n - 2)
}
當(dāng)n過大時(shí),會(huì)報(bào)錯(cuò)!

有以下幾種解決方案:

  • 改循環(huán)
    function fLoop(n, a = 0, b = 1) {  
      while (n--) {
        [a, b] = [b, a + b]
      }
      return a
    }
    
    
    • 尾遞歸優(yōu)化
     function f(n, a=0, b=1) {
        if (n === 0) return a
        return f(n--, b, a+b)
     }
    

如何限制某個(gè)function 只能通過new 調(diào)用?

function Fn(){
        if (!(this instanceof Fn)) {
                console.log('you cant call this function')
                return
        }
        console.log('congratulation!')
}
Fn() // you cant call this function
new Fn() // congratulation

Fn() 直接調(diào)用時(shí) this 指向 window, new 調(diào)用時(shí)將this與構(gòu)造器綁定了,詳情見new 的模擬實(shí)現(xiàn)。

mergeOptions

合并兩個(gè)對(duì)象,生成一個(gè)新對(duì)象。(合并策略為后一個(gè)覆蓋前一個(gè))

const strategy = function (parent, child) {
    return child === undefined
            ? parent
            : child
}
function mergeOption (parent, child) {
    let options = {}
    parent = parent || {}
    function mergeFileds(key) {
        options[key] = strategy(parent[key], child[key])
    }
    for (key in parent) {
        mergeFileds(key)
    }
    for (key in child) {
        if (!Object.prototype.hasOwnProperty.call(parent, key)) {
            mergeFileds(key)
        }
    }
    return options
}
let a = {
    key1: 1,
    key2: 2
}
let b = {
    key2: 22,
    key3: 3
}
mergeOption(a,b) // {key1: 1, key2: 22, key3: 3}

以上是淺拷貝,不能合并嵌套對(duì)象。

let a = {
    key1: 1,
    key2: {
        key21: 21,
        key22: 22
    }
}
let b = {
    key3: 3,
    key2: {
        key22: 222,
        key23: 23
    }
}
mergeOption(a,b) // {key1:1,key2:{key22:222,key23:23},key3:3}

如何能支持嵌套對(duì)象的merge呢? 實(shí)際上只需要改一下strategy即可。

let strategy = function (parent, child) {
    let typeName = function (val) {
        return Object.prototype.toString.call(val).slice(8, -1)
    }
    if (typeName(child) === "Object") {
        return mergeOption(parent, child)
    } else {
        return child === undefined
                ? parent
                : child
    }
}
let a = {
    key1: 1,
    key2: {
        key21: 21,
        key22: 22
    }
}
let b = {
    key1: {key11: 11},
    key3: 3,
    key2: {
        key22: 222,
        key23: 23
    }
}
mergeOption(a,b) // {key1:{key11: 11},key2:{key21: 21,key22:222,key23:23},key3:3}

判斷兩個(gè)對(duì)象相等

export function looseEqual (a: any, b: any): boolean {
  // 當(dāng) a === b 時(shí),返回true
  if (a === b) return true
  // 否則進(jìn)入isObject判斷
  const isObjectA = isObject(a)
  const isObjectB = isObject(b)
  // 判斷是否都為Object類型
  if (isObjectA && isObjectB) {
    try {
      // 調(diào)用 Array.isArray() 方法,再次進(jìn)行判斷
      // isObject 不能區(qū)分是真數(shù)組還是對(duì)象(typeof)
      const isArrayA = Array.isArray(a)
      const isArrayB = Array.isArray(b)
      // 判斷是否都為數(shù)組
      if (isArrayA && isArrayB) {
        // 對(duì)比a、bs數(shù)組的長度
        return a.length === b.length && a.every((e, i) => {
          // 調(diào)用 looseEqual 進(jìn)入遞歸
          return looseEqual(e, b[i])
        })
      } else if (!isArrayA && !isArrayB) {
        // 均不為數(shù)組,獲取a、b對(duì)象的key集合
        const keysA = Object.keys(a)
        const keysB = Object.keys(b)
        // 對(duì)比a、b對(duì)象的key集合長度
        return keysA.length === keysB.length && keysA.every(key => {
          //長度相等,則調(diào)用 looseEqual 進(jìn)入遞歸
          return looseEqual(a[key], b[key])
        })
      } else {
        // 如果a、b中一個(gè)是數(shù)組,一個(gè)是對(duì)象,直接返回 false
        /* istanbul ignore next */
        return false
      }
    } catch (e) {
      /* istanbul ignore next */
      return false
    }
  } else if (!isObjectA && !isObjectB) {
    return String(a) === String(b)
  } else {
    return false
  }
}

以上部分實(shí)現(xiàn)來自Vue源碼

?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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