Okay, I'm a little stumped. I'm probably missing something blatantly obvious but apparently I just can't see the forest for the trees:
I'm trying to call a JavaScript function that expects its parameter to be an array, i.e. it checks if (arg instanceof Array)...
Unfortunately, I (or Rhino) just can't seem to create such an array:
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
String src = "function f(a) { return a instanceof Array; };";
cx.evaluateString(scope, src, "<src>", 0, null);
Function f = (Function) scope.get("f", scope);
Object[] fArgs = new Object[]{ new NativeArray(0) };
Object result = f.call(cx, scope, scope, fArgs);
System.out.println(Context.toString(result));
Context.exit();
And alas, result
is false
.
What am I missing here?
Edit:
Just a little more information: both [] instanceof Array
and new Array() instanceof Array
return true
as one would expect. If I add elements to the array they show up in the JavaScript code with the right indices (numeric, starting from zero):
NativeArray a = new NativeArray(new Object[]{ 42, "foo" });
When output using this JavaScript function:
function f(a) {
var result = [];
result.push(typeof a);
for (var i in a) {
result.push(i + ' => ' + a[i]);
}
return result.join('\\n');
}
The result is:
object
0 => 42
1 => foo
So it works. Except that I want a 'real' array :)
a instanceof Array
) is reasonable, but limited. For instance, even without Rhino, it would fail to identify an array in a browser-based application if that array originated in another window. Would you try addingresult.push(Object.prototype.toString.call(a));
to your function? It'll be interesting to see whether it says[object Object]
or[object Array]
. The latter would be similar to an array from another window, the former would indicate thatNativeArray
wasn't quite what the name implies. – MayNativeArray
? Because there doesn't seem to be any here: mozilla.org/rhino/apidocs – Maynew NativeArray()
is the same as callingContext.newArray()
mxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/… – AsterismObject.prototype.toString.call(a)
returns[object Array]
– Asterism