typeof 与 instanceof的简单的应用
比较数据类型
- 比较简单的数据类型 typeof
typeof 运算符把类型信息当作字符串返回。typeof 返回值有六种可能: “number,” “string,” “boolean,” “object,” “function,” 和 “undefined.”
我们可以使用typeof来获取一个变量是否存在
示例:
console.log( typeof arr == Integer);
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
// Strings
typeof "bla" === 'string';
// Booleans
typeof true === 'boolean';
// Undefined
typeof undefined === 'undefined';
// Functions
typeof function(){} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';
对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。
如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。
- 比较复杂的数据类型 instanceof
instanceof用于判断一个变量是否某个对象的实例,instanceof 左操作数是一个类,右操作数是标识对象的类。
instanceof 运算符是用来测试一个对象是否在其原型链原型构造函数的属性。其语法是 object instanceof constructor
console.log(arr instanceof Array);
var a=new Array();
alert(a instanceof Array); //true,
alert(a instanceof Object)//true
function test(){};
var a=new test();
alert(a instanceof test) //true。