JS基础篇:3、typeof和instanceof

533 阅读1分钟

typeof

用途: 用来检查数据类型,输出的是一个string值。

用法:typeof X / typeof(X)

返回结果: numberstringundefinedobjectbooleanfunctionsymbolES6新增

console.log(typeof x);  // undefined  
console.log(typeof true); // boolean
console.log(typeof 1); // number
console.log(typeof undefined);  // undefined
console.log(typeof function() {});  // function
console.log(typeof null); // object
console.log(typeof [1, 2, 3]); // object
console.log(typeof new Date()); // object
console.log(typeof new RegExp('hello world', 'g')); // object

可以看出来typeof 在检测未声明变量X时候返回undefined 在检测数组和null的时候返回的都是object,所以typeof可以判断数据类型,但是无法判断array和object

instanceof

用途:判断某个变量是否为某一对象的实例

用法:a instanceof b

返回结果:Boolean值

console.log('string' instanceof String);  // false
console.log(true instanceof Boolean); // false
console.log(1 instanceof Number);  // false
console.log(undefined instanceof Object); // false
console.log(null instanceof Object);  // false

console.log(x instanceof Object); // 报错 x is not defined
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、1等)都不能算是对象的实例,而new的一般都可以,未定的x调用instanceof会报错。

Object.prototype.toString()

用途:返回一个对象的字符串

toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。

对于 Object 对象,直接调用 toString()  就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。

console.log( Object.prototype.toString.call('')) ;  // [object String]
console.log( Object.prototype.toString.call(1)) ;   // [object Number]
console.log( Object.prototype.toString.call(true)) ;// [object Boolean]
console.log( Object.prototype.toString.call(Symbol()));//[object Symbol]
console.log( Object.prototype.toString.call(undefined));// [object Undefined]
console.log( Object.prototype.toString.call(null)) ;// [object Null]
console.log( Object.prototype.toString.call([])) ;// [object Array]
console.log( Object.prototype.toString.call({})) ;// [object Object]
console.log( {}.toString()) ;// [object Object]