typeof
ECMAScript是松散类型的,一次需要一种手段来检测给定变量的数据类型,typeof操作符(注意不是函数哈!)就是负责提供这方面信息的,typeof 可以用于检测基本数据类型和引用数据类型。
语法格式如下:
typeof variable
返回6种String类型的结果:
- "undefined" - 如果这个值未定义
- "boolean" - 如果这个值是布尔值
- "string" - 如果这个值是字符串
- "number" - 如果这个值是数值
- "object" - 如果这个值是对象或null
- "function" - 如果这个值是函数
示例:
console.log(typeof 'hello'); // "string"
console.log(typeof null); // "object"
console.log(typeof (new Object())); // "object"
console.log(typeof(function(){})); // "function"
typeof主要用于检测基本数据类型:数值、字符串、布尔值、undefined, 因为typeof用于检测引用类型值时,对于任何Object对象实例(包括null),typeof都返回"object"值,没办法区分是那种对象,对实际编码用处不大。
instanceof
在检测基本数据类型时typeof是非常得力的助手,但在检测引用类型的值时,这个操作符的用处不大,通常,我们并不是想知道某个值是对象,而是想知道它是什么类型的对象。此时我们可以使用ECMAScript提供的instanceof操作符。
语法格式如下:
result = variable instanceof constructor
返回布尔类型值:
- true - 如果变量(variable)是给定引用类型的实例,那么instanceof操作符会返回true
- false - 如果变量(variable)不是给定引用类型的实例,那么instanceof操作符会返回false
示例:
function Person(){
}
function Animal(){
}
var person1 = new Person();
var animal1 = new Animal();
console.log(person1 instanceof Person); // true
console.log(animal1 instanceof Person); // false
console.log(animal1 instanceof Object); // true
console.log(1 instanceof Person); //false
根据规定,所有引用类型的值都是Object的实例。因此,在检测一个引用类型值和Object构造函数时,instanceof操作符会始终返回true。如果使用instanceof 操作符检测基本类型值时,该操作符会始终返回false,因为基本类型不是对象。
如果要做一个更加完整的检验,需要使用typeof和instanceof结合使用。
如果要做一个更加完整的检验,需要使用typeof和instanceof结合使用。