js数据类型

604 阅读2分钟

js

对于js,我们再熟悉不过了,在项目开发中经常用到js。那对于js数据类型你了解多少呢?下面我们一起来探讨下js数据类型吧。

js数据类型分为两类:

值类型(基本类型):字符串(String)、数字(Number)、布尔(Boolean)、对空(Null)、未定义(Undefined)、Symbol。

引用数据类型:对象(Object)、数组(Array)、函数(Function)。

注:Symbol 是 ES6 引入了一种新的原始数据类型,表示独一无二的值。

我们怎么去区分这个变量到底是基本类型还是引用数据类型呢?这里我要介绍下 typeof 这个方法。

var str = 'string';
var num = 1;
var bool = true;
var n = null;
var u = undefined;
var s = Symbol();
var obj = {name: 'li'};
var arr = [1, 2];
var fun = function() { return 1 };

typeof(str) // "string"
typeof(num) // "number"
typeof(bool) // "boolean"
typeof(n) // "object"
typeof(u) // "undefined"
typeof(s) // "symbol"
typeof(obj) // "object"
typeof(arr) // "object"
typeof(fun) // "function"

可以看到,通过 typeof 这个方法我们很好地区别了基本类型和引用数据类型。

当然,细心地小伙伴回发现Null和引用数据类型无法区分,因为他们都输出了"object",那么我们该怎么区分null和引用类型呢?这里我要介绍 instanceof 这个方法。

var n = null;
var obj = {name: 'li'};
var arr = [1, 2];
var fun = function() { return 1 };

n instanceof Object; // false
obj instanceof Object; // true
arr instanceof Array; // true
fun instanceof Function; // true

可以看到,通过 instanceof 这个方法,我们很快地区分了Null和引用数据类型。

关于如何区分基本类型和引用数据类型,我就介绍到这里。下面我们来看下如何区分引用类型变量到底是数组、对象还是函数呢?这里我要介绍 Object.prototype.toString.call() 这个方法

var str = 'string';
var num = 1;
var bool = true;
var n = null;
var u = undefined;
var s = Symbol();
var obj = {name: 'li'};
var arr = [1, 2];
var fun = function() { return 1 };

Object.prototype.toString.call(str); // "[object String]"
Object.prototype.toString.call(num); // "[object Number]"
Object.prototype.toString.call(bool); // "[object Boolean]"
Object.prototype.toString.call(n); // "[object Null]"
Object.prototype.toString.call(u); // "[object Undefined]"
Object.prototype.toString.call(s); // "[object Symbol]"
Object.prototype.toString.call(obj); // "[object Object]"
Object.prototype.toString.call(arr); // "[object Array]"
Object.prototype.toString.call(fun); // "[object Function]"

可以看到,通过 Object.prototype.toString.call() 这个方法,不仅可以快速基本类型和引用数据类型,还是区分引用类型是数组、对象还是函数

总结

js数据类型就分享到这里了,欢迎交流哈!