2013-04-26 117 views
13

如何知道對象是否是數組?識別數組對象

var x=[]; 

console.log(typeof x);//output:"object" 
alert(x);//output:[object Object] 
console.log(x.valueOf())//output:<blank>? what is the reason here? 
console.log([].toString()); also outputs <blank>  
Object.prototype.toString.call(x) output:[object Array] how? 

因爲console.log([]。toString());輸出:空白

1:

爲什麼我會在第二屆最後一條語句空白?

第二:

有沒有辦法確切地知道什麼是對象:沒有各自喜歡x.join方法(幫助陣列或普通對象({}))表示x是數組,不是這樣。

事實上,在jQuery的選擇像$(「P」)返回jQuery對象,所以如果我使用

console.log(typeof $("p"));//output:"object 

我只是想知道實際名稱的Object.Thats it.Thank u表示ü幫助

+0

看看這個問題,其他 http://stackoverflow.com/questions/767486/how-do-you-check-if- a-variable-is-an-array-in-javascript – acj 2013-04-26 11:18:57

回答

8

在純JavaScript,你可以使用下面的跨瀏覽器的方法:

if (Object.prototype.toString.call(x) === "[object Array]") { 
    // is plain array 
} 

jQuery有special method爲:

if ($.isArray(x)) { 
    // is plain array 
} 
+0

console.log([]。valueOf())//輸出:?這裏的原因是什麼? – 2013-04-26 11:25:48

+0

@Maizere基本上'[] .valueOf()'返回'[]',這裏沒有任何意義。 – VisioN 2013-04-26 11:27:38

+0

謝謝你,它幫助 – 2013-04-26 11:29:52

1

簡單:

if(Object.prototype.toString.call(someVar) === '[object Array]') { 
    alert('Array!'); 
} 
2

最佳實踐是Object.prototype.toString()目標對象,其中顯示了內部[[Class]]屬性名稱上調用。

Object.prototype.toString.call(x); // [object Array] 

這有adventage,它適用於任何和每一個物體上,不管你是在一個多幀/窗口環境,這將導致使用x instanceof Array問題的工作。


較新的ES5實現,也給你的方法Arrays.isArray(),它返回truefalse

Array.isArray(x); // true 

最後但並非最不重要的是,jQuery擁有自己.isArray()方法,這也返回一個布爾值

jQuery.isArray(x); // true 
0

我認爲你正在尋找的是這樣的:

if(Object.prototype.toString.call(someVar) === '[object Array]') { 
    alert('Array!'); 
} 

希望這會有所幫助。有點慢:P

+1

是的,這已經發布了兩三次了。 – 2013-04-26 11:21:07

3

您可以使用instanceof。下面是一些螢火測試:

test1 = new Object(); 
 
test2 = new Array(); 
 
test3 = 123; 
 

 
console.log(test1 instanceof Array); //false 
 
console.log(test2 instanceof Array); //true 
 
console.log(test3 instanceof Array); //false

+1

也許downvoter會友好地解釋爲什麼-1,爲了學習:) – LeonardChallis 2013-04-26 11:25:50

+1

是不是我(坦率地說,我不認爲這是錯的,應該得到一個downvote),但是這在多方面失敗了, DOM環境,如iframe等。有關更多信息,請參閱[本文](http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/)。 – 2013-04-26 11:30:03

+0

很好 - 謝謝:) – LeonardChallis 2013-04-26 11:34:31