Js 常用方法及问题汇总

数组扁平化

  • 常规方法:
    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的原型。(由此就会造成误解 [] 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]
    ...
    

    但是据说ie6下有问题, string,null,undefined会误判断为object(未考证!)

递归爆栈问题

function f(n) {
  if (n === 0 || n === 1) return n 
  else return f(n - 1) + f(n - 2)
}
当n过大时,会报错!

有以下几种解决方案:

  • 改循环
    function fLoop(n, a = 0, b = 1) {  
      while (n--) {
        [a, b] = [b, a + b]
      }
      return a
    }
    
    
    • 尾递归优化
     function f(n, a=0, b=1) {
        if (n === 0) return a
        return f(n--, b, a+b)
     }
    

如何限制某个function 只能通过new 调用?

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() 直接调用时 this 指向 window, new 调用时将this与构造器绑定了,详情见new 的模拟实现。

mergeOptions

合并两个对象,生成一个新对象。(合并策略为后一个覆盖前一个)

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}

以上是浅拷贝,不能合并嵌套对象。

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}

如何能支持嵌套对象的merge呢? 实际上只需要改一下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}

判断两个对象相等

export function looseEqual (a: any, b: any): boolean {
  // 当 a === b 时,返回true
  if (a === b) return true
  // 否则进入isObject判断
  const isObjectA = isObject(a)
  const isObjectB = isObject(b)
  // 判断是否都为Object类型
  if (isObjectA && isObjectB) {
    try {
      // 调用 Array.isArray() 方法,再次进行判断
      // isObject 不能区分是真数组还是对象(typeof)
      const isArrayA = Array.isArray(a)
      const isArrayB = Array.isArray(b)
      // 判断是否都为数组
      if (isArrayA && isArrayB) {
        // 对比a、bs数组的长度
        return a.length === b.length && a.every((e, i) => {
          // 调用 looseEqual 进入递归
          return looseEqual(e, b[i])
        })
      } else if (!isArrayA && !isArrayB) {
        // 均不为数组,获取a、b对象的key集合
        const keysA = Object.keys(a)
        const keysB = Object.keys(b)
        // 对比a、b对象的key集合长度
        return keysA.length === keysB.length && keysA.every(key => {
          //长度相等,则调用 looseEqual 进入递归
          return looseEqual(a[key], b[key])
        })
      } else {
        // 如果a、b中一个是数组,一个是对象,直接返回 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
  }
}

以上部分实现来自Vue源码

你可能感兴趣的:(Js 常用方法及问题汇总)