JavaScript数据类型

290 阅读1分钟

数据类型

ECMAScript包括两个不同类型的值:基本数据类型和引用数据类型

基本数据类型

String、 Number、 Boolean、 Null、 Undefined、 Symbol (ECMAScript 6 新定义)

基本数据类型是指存放在栈中的简单数据段,数据大小确定,内存空间大小可以分配,它们是直接按值存放的,所以可以直接按值访问。

引用数据类型

Object(在JS中除了基本数据类型以外的都是对象,数据是对象,函数是对象,正则表达式是对象)。

引用类型是存放在堆内存中的对象,变量其实是保存的在栈内存中的一个指针(保存的是堆内存中的引用地址),这个指针指向堆内存

typeof检测数据类型

> typeof "abc"   "string" 字符串
> typeof abc     "undefined" 未定义
> typeof 0       "number" 数值
> typeof null    "object" 对象或者 null
> typeof console.log  "function" 函数
> typeof true         "boolean" 布尔类型值

数据类型正确判断方法

Object.prototype.toString.call(variable)

用这个方法来判断数据类型目前是最可靠的了,它总能返回正确的值

该方法返回 "[object type]", 其中type是对象类型。

Object.prototype.toString.call(null) "[object Null]"
Object.prototype.toString.call([]); "[object Array]"
Object.prototype.toString.call({}); "[object Object]"
Object.prototype.toString.call(123); "[object Number]"
Object.prototype.toString.call('123'); "[object String]"
Object.prototype.toString.call(false); "[object Boolean]"
Object.prototype.toString.call(undefined); "[object Undefined]"

typeof检测数据类型

String Boolean Number Undefined 四种基本类型的判断 除了 Null 之外的这四种基本类型值,都可以用 typeof 操作符很好的进行判断处理。

使用 === 判断null

除了 Object.prototype.toString.call(null) 之外,目前最好的方法就是用 variable === null 全等来判断了。

var a = null;
if (a === null) {
    console.log('a is null');
}
//  a is null
a is null