Array和Object类型判断方法比较

2020-05-19  本文已影响0人  伪球迷也是球迷啊

判断Array

  1. typeof 返回object
console.log(typeof []) // "object"
typeof 1; // "number"
typeof null; "object"
typeof undefined; "undefined"
typeof function; "function"
  1. instanceof
arr instanceof Array; // true
  1. constructor
arr.constructor === Array; // true

2和3方法都是对原型链进行检测,但如果是跨iframe实例化的对象彼此是不共享原型链的,会导致上述方法失效

  1. Object.prototype.toString
Object.prototype.toString.call([]) === '[object Array]'; // true
Object.prototype.toString.call({}) === '[object Object]';  // true
  1. Array.isArray();
    ES5方法,ie8之前不支持

判断Object

判断数组的2,3,4方法同样适用

其他数据类型判断

typeof 判断即可

Object.is 与 === 区别是

// 使用 ‘===’
+0 === -0 //true
NaN === NaN // false
// 使用 Object.is()
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

深浅拷贝函数

  1. 递归实现
function deepClone(source) {
  let target;
  if (typeof source === 'object') {
    target = Array.isArray(source) ? [] : {}
    for (let key in source) {
      if (source.hasOwnProperty(key)) {
        if (typeof source[key] !== 'object') {
          target[key] = source[key]
        } else {
          target[key] = deepClone(source[key])
        }
      }
    }
  } else {
    target = source
  }
  return target
}
  1. JSON序列化实现
  2. Object.assign({}, object); 如果object字段值是简单类型就是深拷贝,如果值是引用类型就是浅拷贝
  3. 数组拷贝 [...arr]
上一篇 下一篇

猜你喜欢

热点阅读