AndroidJSCore icon indicating copy to clipboard operation
AndroidJSCore copied to clipboard

Best way to tell if a JSValue contains a JSArray

Open cgilboy opened this issue 10 years ago • 2 comments

Hi Eric,

Thanks for this library - it's super helpful!

I'm generating an array of arbitrary types in Javascript that I want to handle on a type-by-type basis in Java. JSValue appears to support reflection methods for identifying undefined, null, boolean, number, string and Object, but not for Array. Is there a good way to identify an Array?

For the moment, I'm considering using JSValues isInstanceOfConstructor with Array.constructor as the argument, but I need to get the result of Array.constructor in Java first and that is extra bookkeeping that I'd rather avoid. I also haven't tested if it works :)

Thanks in advance! Colin

cgilboy avatar Apr 22 '16 16:04 cgilboy

A JavaScript array is nothing more than an object with numeric properties. So this is generally a JavaScript issue. See http://stackoverflow.com/questions/4775722/check-if-object-is-array for a good discussion.

The easiest, but not foolproof, way of testing is to see if it is both an object and contains the length property:

if ( myJSValue.isObject() && !myJSValue.toObject().property('length').isUndefined()) {
    // I am most likely an array
}

You could try something like this (not tested):

JSObject what = context.property('Object').toObject().prototype().toObject().property('toString').toObject();
if (what.callAsFunction(null,new JSValue[] { myJSValue }).toString().isEqualToString("[object Array]")) {
    // I am most definitely an array
}

This is based on the explanation here: http://blog.niftysnippets.org/2010/09/say-what.html

ericwlange avatar Apr 23 '16 05:04 ericwlange

Thanks. I wasn't sure if something like Array.isArray was available natively and could be exposed (or was already exposed) via the JNI somehow.

As of iOS 9 and OS 10.11, Apple has exposed isArray and isDate in their JSValue implementation, but this may rely on newer versions of the underlying core.

For AndroidJSCore v2.0, I've gotten the following to work for strict type checking:

public boolean jsObjectIsArray(JSObject object) throws JSException {
        String constructorName = object.prototype().toObject().property("constructor").toObject().property("name").toString();
        return constructorName.equals("Array");
    }

I've tested this for my use case and it can differentiate between Objects and Arrays. The same could be done for Dates. Please let me know if you see any flaws in it, or if there are any glaring performance issues. Thanks!

cgilboy avatar Apr 25 '16 15:04 cgilboy