2013-05-27 56 views
2

我有這樣的原型;如何確定參數是JavaScript中的數組還是對象?

LocalDataEngine.prototype.ExecuteNonQuery = function (query) { } 

而且我在下面兩個不同的參數中調用這個原型;

通過使用對象數組;

var createQueries = new Array(); 
createQueries.push(new SQLiteQuery("")); 
createQueries.push(new SQLiteQuery("")); 
createQueries.push(new SQLiteQuery("")); 

new LocalDataEngine().ExecuteNonQuery(createQueries); 

通過僅使用對象;

new LocalDataEngine().ExecuteNonQuery(new SQLiteQuery("")); 

我的問題是,我怎麼能確定query論點的原型是對象數組或對象?

+2

http://stackoverflow.com/questions/4775722/javascript-check-if-object-is-array – georg

+0

+這種感覺就像糟糕的設計給我。只需創建兩個函數'executeOneQuery'和'executeManyQueries'。 – georg

+0

你說得對,但我不想改變現有的設計。 –

回答

4

您可以使用instanceof

% js 
> [] instanceof Array 
true 
> {} instanceof Array 
false 

它將如果你不使用框架的工作完美(這可能是一個不好的想法)。如果您使用的框架和ECMAScript 5,使用Array.isArray

> Array.isArray({}) 
false 
> Array.isArray([]) 
true 

見thg435尋找其他解決鏈接的重複問題。

+0

我無法理解您的語法 –

+0

這可能會在多框架DOM環境中失敗。使用Object.prototype.toString更安全,請參閱:http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ – David

+0

@MehmetInce:請參閱[這](http://stackoverflow.com/q/1094723/309483)的文字數組語法的解釋。正如你所看到的,有理由選擇它。 –

2

像這樣:

if (query instanceof Array) { 
    return 'array'; 
} else if (query instanceof Object) { 
    return 'object'; 
} else { 
    return 'scalar'; 
} 
2
if(Object.prototype.toString.call(yourObj) === '[object Array]') { 
    alert('Array!'); 
} 
+0

請參閱[本](http://stackoverflow.com/a/4775737/309483)以獲得解釋 –

+0

+1。這也是jQuery在'$ .isArray()'背後使用的內容。 – David

相關問題