JavaScript基础总结

值类型和引用类型

  • 可以使用typeof来进行判断,typeof可以判断出所有的值类型
let a;
const str = 'abc';
const b = true;
const s = Symbol('s');
typeof a; // undefined
typeof str; // string
typeof b; // boolean
typeof s; // symbol
  • typeof还能判断出函数类型
typeof console.log; // function
typeof function () {}; // function
  • typeof能识别出引用类型,但是不能再继续识别
typeof null // object
typeof [ 'a', 'b' ] // object
typeof { x: 100 } // object

深拷贝的实现

const obj = {
  age: 20,
  name: 'xxx',
  address: {
    city: '成都',
  },
  arr: ['a', 'b', 'c']
}

function deepClone(obj = {}) {
  if (typeof obj !== 'object' || obj == null) {
    return obj
  }
  let result
  if (obj instanceof Array) {
    result = []
  } else {
    result = {}
  }
  for (let key in obj) {
    // 保证 key 不是原型的属性
    if (obj.hasOwnProperty(key)) {
      // 递归
      result[key] = deepClone(obj[key])
    }
  }
  return result
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容