typeof和instanceof简介及用法

typeof

  使用方式:typeof a 或者 typeof (a) 返回一个string类型的值

  顾名思义,这货是检查类型的,输出的是一个string值,直接看下面的检测代码:

复制代码
console.log(typeof 'i am a string');  // string                         
console.log(typeof true); // boolean
console.log(typeof 10); // number
console.log(typeof undefined);  // undefined
console.log(typeof function() {});  // function
console.log(typeof null); // object
console.log(typeof new String('i am a string')); // object
console.log(typeof new Boolean(true)); // object
console.log(typeof new Number(10)); // object
console.log(typeof [1, 2, 3, 4]); // object
console.log(typeof new Array(1, 2, 3, 4)); // object
console.log(typeof new Date()); // object
console.log(typeof new RegExp('hello world', 'g')); // object
console.log(typeof /hello/g); // object
复制代码

  这货最大的短板就是对null和数组的检测不利(都只能返回object)!

  typeof除了能初步检测变量的类型外,还能判断一个变量是否为空(没赋值或者没声明):

复制代码
var a;
if(typeof a === 'undefined') {  
  console.log('hello'); // hello
}

if(a === undefined) {
  console.log('world')  // world
}
复制代码

  有趣的是没赋值和没声明的元素经过typeof运算后得到的结果一样,都是“undefined”字符串(因为本来就都是typeof undefined):

var a;
console.log(typeof a === typeof b); // true

  这时该如何区别?可以用 in window 判断:

var a;
console.log('a' in window); // true
console.log('b' in window); // false

  相对于instanceof,typeof还是比较简单的~

 instanceof

  使用方式:a instanceof b 返回一个boolean

  instanceof的英文解释是实例,它的作用是判断某个变量是否为某一对象的实例。看检测代码:

复制代码
console.log('string' instanceof String);  // false
console.log(true instanceof Boolean); // false
console.log(10 instanceof Number);  // false
console.log(undefined instanceof Object); // false
console.log(null instanceof Object);  // false

console.log({} instanceof Object);  // true
console.log(new String('string') instanceof String); // true
console.log(new Boolean(true) instanceof Boolean); // true
console.log(new Number(10) instanceof Number); // true
console.log([] instanceof Array); // true
console.log(new Array() instanceof Array); // true
console.log(new Date() instanceof Date); // true
console.log(new RegExp('') instanceof RegExp); // true
console.log(/hello/ instanceof RegExp); // true
复制代码

   我们可以看到,instanceof规定基本数据类型(比如'string'、true、10等)都不能算是对象的实例,而new的一般都算。

   instanceof的第一个值(即a instanceof b中的a)必须先进行过声明,不然报错;而typeof则可对未声明变量进行判断(返回"undefined")

posted on 2017-04-07 16:06  郑兴鹏  阅读(324)  评论(0编辑  收藏  举报

友情链接:上海回力鞋专卖店 | 中老年高档女装 | 新航道 | 雅思培训一般多少钱 | 托福网课