如果用 typeof 判断类型时,array,object和null类型都是 object,所以无法区分数组和对象。以下是几种清晰判断数组的方法:
var arr =[];
var obj = {};
var str = '';
-
方法一:IsArray()
Array.isArray(arr); // true
-
方法二:instanceof
arr instanceof Array; // true
-
方法三:constructor
a.constructor; // ƒ Array() { [native code] }
arr.constructor == Array; // true;
-
方法四:toString()
Object.prototype.toString.call(arr); // "[object Array]"
Object.prototype.toString.call(obj); // "[object Object]"
Object.prototype.toString.call(str); // "[object String]"