2012-06-13 62 views
0

我已經嘗試了三種方法,結果是右邊的評論,難度是我不能不同它從Object數據類型。我怎樣才能得到它的數據類型,如ArrayString但不是Object如何判斷一個javascript變量的數據類型是Array?

var arr = []; 
    console.log('type of arr', typeof arr); //objct 
    console.log('instanceof array', arr instanceof Array); //true 
    console.log('instanceof object', arr instanceof Object); // true 
+0

順便說一句,[這已經問(http://stackoverflow.com/questions/4775722/javascript-check-if-object -is陣列)。 – voithos

回答

0

陣列始終將對象的實例 - Object是JavaScript和任何由新創建的另一個目的是繼承基礎對象從。

new String('a') instanceof Object // true - also instance of String 
new Number(3) instanceof Object // true -also instance of Number etc. 
new Boolean(true) instanceof Object // true 
new Date instanceof Object // true 
new function(){} instanceof Object // true 

[] instanceof Object // true - [] is equal to new Array 

check this out: 
Array = 1; 
[] //TypeError: Cannot read property 'slice' of undefined 
:) 

然而

'a' instanceof Object // false 
3 instanceof Object // false 

試試這個:

var str = 'aaa', 
    arr = [], 
    myClass = function(){}, 
    myClassInstance = new myClass; 

str.constructor == String // true 
arr.constructor == Array // true 
myClassInstance.constructor == myClass // true 
+0

(new Date(3)instanceof Object)返回true。雖然您可以創建新日期(3)並獲取有效日期,但3不是日期,而是數字。在陣列檢測的範圍內,這種方法可能有效,但所描述的擴展答案對於其他用法具有誤導性。 –

3

這裏有一個技巧:

> var arr = []; 
> Object.prototype.toString.call(arr); 
"[object Array]" 

這樣做是調用原型對象的toString方法,使用任何傳入的this指針。有關此技術的更多信息,請參閱the reference on call

事實證明,你可以使用這種技術來找出其他對象類型,以及:

> var func = function(){} 
> Object.prototype.toString.call(func); 
"[object Function]" 

> var obj = {}; 
> Object.prototype.toString.call(obj); 
"[object Object]" 
0

這是很簡單的,你的問題確實是你的答案,

var arr = []; 
if('instanceof object', arr instanceof Object){ 
    alert('arr is a object'); 
    if('instanceof array', arr instanceof Array){ 
     alert('arr is a Array'); 
    } 
}​else{ 
    alert('this is not a object'); 
} 

現在,讓我們使用一個簡單的變量testObj,這甚至不是一個對象,那麼它怎麼可能是一個數組,

var testObj; 
    if('instanceof object', testObj instanceof Object){ 
     alert('testObj is a object'); 
    }else{ 
     alert('testObj is not a object'); 
    } 
​ 

嘗試此more

3

你可以使用jQuery的「IsArray的」功能這一

var arr1 =[]; 
alert(jQuery.isArray(arr1)); // true 

var arr2 = new Array(); 
alert(jQuery.isArray(arr2)); // true 

var obj = new Object(); 
alert(jQuery.isArray(obj)); // false 
1

我在MDN此信息 - 在Javascript版本加入1.8.5 Array.isArray,它在ECMAScript中5標準

// all following calls return true 
Array.isArray([]); 
Array.isArray([1]); 
Array.isArray(new Array()); 
Array.isArray(Array.prototype); // Little known fact: Array.prototype itself is an array. 

另外,如果isAr射線不可

if(!Array.isArray) { 
    Array.isArray = function (vArg) { 
    return Object.prototype.toString.call(vArg) === "[object Array]"; 
    }; 
} 

有關詳細信息在MDN

相關問題