February 17, 2017

JavaScript Array类型的变量使用typeof结果为Object

问题描述

在业务系统中,写了一个方法并要求传入一个参数,参数必须为一个数组,但使用typeof去检查的时候发现并不能获得想要的Array字符。

var a = [1, 2, 3];
console.log(a);         // Array[3]
console.log(typeof a);  // "object"

结果表明,使用typeof并不能得到原计划中的Array

typeof可以检测基本类型包括 undefined, string, number, boolean,但是对于检测对象就不靠谱了。不只是Array,javascript中的对象,包括 Date, String, Boolean, Number, Object, Function, Array, RegExp, Error 使用typof只会返回 "object"

使用 instanceof 或者 constructor 来检测 Array 也不是靠谱的办法。

解决方案

ECMA中对Object.prototype.toString的解释:

When the toString method is called, the following steps are taken:

  1. Get the http://Class property of this object.
  2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
  3. Return Result (2)

其过程简单说来就是:1、获取对象的类名(对象类型)。2、然后将[object 类型]组合并返回。

另外,使用Object.prototype.toString,而不是Object.toString是因为toString可能被覆写。

var type=function(object){
  return Object.prototype.toString.call(object);
}

type({}) //"[object Object]"
type([1,2,3,4]); //"[object Array]"
type(new Date()); //"[object Date]"
type(/^hello/); //"[object RegExp]"
type(new Error()) //"[object Error]"
type(new Number()) //"[object Number]"

参考:https://segmentfault.com/q/1010000000130605