数据类型
- ES5种数据类型
5种基本数据类型:String, Number, Null, Boolean, Undefined
1种复杂数据类型:Object
+ 基本数据类型是可以直接操作值的数据类型
复杂数据类型是由基本数据类型构成的一种类型
- ES6新增第六种基本数据类型
Symbol
+ 常用于给对象属性命名,生成唯一属性名,防止命名冲突
- 值类型
string, boolean, undefined, number, null, Symbol
- 引用类型
function, array, object
- 判断数据类型的方法
1. typeof
typeof可以判断基本数据类型,除了null,null表示的是空对象指针。
1
2
3
4
5
6
7
8
9
10
11
12
typeof('string') //"string"
typeof('undefined') //"undefined"
typeof(1) //"number"
typeof(Symbol()) //"symbol"
typeof(undefined) //"undifined
typeof((function a(){})) //"function
typeof([]) //"object"
typeof(null) //"object"
typeof({}) //"object"
2. instanceof
instanceof用于检测构造函数的prototype是否出现在某个实例对象的原型链里。只能判断引用类型
1
2
3
[] instanceof Array //true
(function a(){}) instanceof Function //true
{} instanceof Object //true
所有的类型都指向Object,因为js的本质就是原型链,实际上只有一种数据类型,就是对象。
SO...
1
2
3
4
5
6
7
Array instanceof Object //true
Function instanceof Object //true
Number instanceof Object //true
String instanceof Object //true
Symbol() instanceof Object //true
null instanceof Object //true
undefined instanceof Object //true
3. constructor
> 返回创建实例对象的 Object 构造函数的引用。注意,此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。对原始类型来说,如1,true和"test",该值只可读。
null, undefined无法使用constructor属性。
由于类与继承,导致constructor可改变,有时无法判断其构造函数引用。
1
2
3
4
5
6
7
8
9
10
11
[].constructor == Array //true
var a={};
a.constructor == Object //true
a=1;
a.constructor == Number //true
a=true;
a.constructor == Boolean //true
a="1"
a.constructor == String //true
a=Symbol
a.constructor == Symbol //true
4. Object.prototype.toString.call();
> 每个对象都有一个 toString() 方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString() 方法被每个 Object 对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。
在未被覆盖的情况下,该方法可输出任意类型的类型名。