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?

4
  • 2
    stackoverflow.com/questions/4775722/… Commented May 27, 2013 at 11:05
  • + this feels like bad design to me. Just make two functions executeOneQuery and executeManyQueries. Commented May 27, 2013 at 11:09
  • You're right, but I dont want to change existing design. Commented May 27, 2013 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. Commented May 27, 2013 at 11:36

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I couldn't understand your syntax
This can fail in multi-frame DOM environments. It’s more safe to use Object.prototype.toString, see here: perfectionkills.com/…
@MehmetInce: See this for an explanation of the literal array syntax. As you can see, there are reasons to prefer it.
frames = bad. iFrames = still very common (f.ex video embeds).
2

Like this:

if (query instanceof Array) {
    return 'array';
} else if (query instanceof Object) {
    return 'object';
} else {
    return 'scalar';
}

Comments

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

1 Comment

+1. This is also what jQuery uses under the hood for $.isArray().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.