js基本类型和引用类型

版权声明: https://blog.csdn.net/weixin_41826907/article/details/79892427

js数据类型可以分为基本类型和引用类型:

基本类型的值源于以下5种基本数据类型:
UndefinedNull、Boolearn、NumberString

*基本类型值在内存中占据固定大小空间,因此保存在栈内存中
*从一个变量向另一个变量复制基本类型,会创建这个值的一个副本

确定一个值是哪种基本类型可以使用typeof操作符
typeof返回值对应表:

Undefined   "undefined"
Null    "object"(见下文)
Boolean "boolean"
Number  "number"
String  "string"
Symbol (ECMAScript 6 新增)    "symbol"
宿主对象(由JS环境提供)   Implementation-dependent
函数对象([[Call]] 在ECMA-262条款中实现了)  "function"
任何其他对象  "object"
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写
typeof Number(1) === 'number'; // 但不要使用这种形式!

// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof总是返回一个字符串
typeof String("abc") === 'string'; // 但不要使用这种形式!

// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // 但不要使用这种形式!

// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';

// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 

// Objects
typeof {a:1} === 'object';

// 使用Array.isArray 或者 Object.prototype.toString.call
// 区分数组,普通对象
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';

// 下面的容易令人迷惑,不要使用!
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String("abc") === 'object';

// 函数
typeof function(){} === 'function';
typeof class C{} === 'function'
typeof Math.sin === 'function';
typeof new Function() === 'function';
引用类型

引用类型的值是引用类型的一个实例,确定一个值是哪种引用类型可以使用instanceof操作符

Object类型,
Array类型,
Date类型,
RegExp类型,
Function类型,
基本包装类型:Boolean类型、Number类型、String类型,
单体内置对象: Global对象、Math对象

*保存在堆内存中(java中还有方法区啥的,姑且先理解为全在堆内存中)
*从一个变量向另一个变量复制基本类型,复制的是一个指针

object instanceof constructor

instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
对于基本包装类型,它们是基本类型值可以被当作对象来访问,它们的共同特点是:

*每个包装类型都映射到同名的基本类型
*在读取模式下访问基本类型值时,就会创建对应的基本包装类型的一个对象,从而方便了数据操作
*操作基本类型的语句一经执行完毕,就会立即销毁新创建的包装对象

猜你喜欢

转载自blog.csdn.net/weixin_41826907/article/details/79892427