好吧,我有点难过。我可能错过了一些明显的东西,但显然我只是看不到森林的树木:
我正在尝试调用一个期望其参数为数组的 JavaScript 函数,即它检查if (arg instanceof Array)...
不幸的是,我(或 Rhino)似乎无法创建这样的数组:
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();
唉,result
是false
。
我在这里想念什么?
编辑:
再多一点信息:两者都[] instanceof Array
按预期new Array() instanceof Array
返回。true
如果我将元素添加到数组中,它们会以正确的索引(数字,从零开始)显示在 JavaScript 代码中:
NativeArray a = new NativeArray(new Object[]{ 42, "foo" });
使用此 JavaScript 函数输出时:
function f(a) {
var result = [];
result.push(typeof a);
for (var i in a) {
result.push(i + ' => ' + a[i]);
}
return result.join('\\n');
}
结果是:
object
0 => 42
1 => foo
所以它有效。除了我想要一个“真正的”数组:)