2

I have a prototype like this;

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

And I call this prototype within two different argument like below;

By using object array;

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

new LocalDataEngine().ExecuteNonQuery(createQueries);

By using only object;

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

My question is, how can I determine query argument in prototype is object array or object?

Steven Moseley
  • 13,831
  • 4
  • 32
  • 42
Mehmet Ince
  • 3,625
  • 10
  • 40
  • 64
  • 2
    http://stackoverflow.com/questions/4775722/javascript-check-if-object-is-array – georg May 27 '13 at 11:05
  • + this feels like bad design to me. Just make two functions `executeOneQuery` and `executeManyQueries`. – georg May 27 '13 at 11:09
  • You're right, but I dont want to change existing design. – Mehmet Ince May 27 '13 at 11:11
  • Regarding the design, why don't you make `ExecuteNonQuery` variadic, i.e. accept multiple arguments where each one is a query. Then always iterate over all arguments. – Felix Kling May 27 '13 at 11:36

3 Answers3

4

You can use instanceof:

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

It will work flawlessly if you are not using frames (which is probably a bad idea anyway). If you are using frames and ECMAScript 5, use Array.isArray:

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

See the duplicate question linked by thg435 for additional solutions.

Janus Troelsen
  • 17,537
  • 13
  • 121
  • 177
2

Like this:

if (query instanceof Array) {
    return 'array';
} else if (query instanceof Object) {
    return 'object';
} else {
    return 'scalar';
}
Steven Moseley
  • 13,831
  • 4
  • 32
  • 42
2
if( Object.prototype.toString.call( yourObj) === '[object Array]' ) {
    alert( 'Array!' );
}
Pranav
  • 7,315
  • 4
  • 23
  • 40