js深刻理解--数据类型

数据类型

js中的基本数据类型, 分别为 string, number, boolean, undefined, function, object, symbol 以及未来的 BigInt.

值类型

保存在 中, 每次复制与赋值操作的都是变量本身的值

const a = 1;
const b = 1;
const c = true;
const d = false;
console.log(a === b); // true
console.log(c === d); // true

注意: 简单类型 !== 值类型

const a = 1;
const b = new Number(1);

a === b; // ? false
a.length = 2;
b.length = 2;
a.length // ? undefined
b.length // ? 2

// 大坑
const c = new String('');
c.length // ? 0
c.length = 2;
c.length // ? 0

引用类型

保存在堆中, 在赋值等操作实际操作的是对象的内存地址.

  1. function外, 通过 typeof 不能判断其准确类型
  2. 在操作引用类型是一定注意深拷贝和浅拷贝
  3. 使用 instanceofObject.prototype.toString.call 来判断其精确类型
const a = {};
const b = {};
a === b; // false

const a = {test: 1};
const b = a;
b.test = 2;
a.test // 2
// 分析
// eg1
a = {n: 1};
a.x = a = {n: 2}
a.x  // ?

// eg2

a = {n: 1};
b = a;
a.x = a = {n: 2}
a.x // ?
b.x // ?
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容