如何在Rhino中创建一个“真正的”JavaScript数组 [英] How to create a 'real' JavaScript array in Rhino
问题描述
好的,我有点难过。我可能错过了一些显而易见的东西,但显然我只是看不到森林的树木:
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:
我正在尝试调用一个需要参数的JavaScript函数成为一个数组,即它检查 if(arg instanceof Array)...
不幸的是,我(或Rhino)似乎无法创建这样的数组:
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();
唉,结果
是 false
。
我在这里缺少什么?
编辑:
更多信息: [] instanceof Array
和 new Array()instanceof数组
返回 true
正如人们所期望的那样。如果我向数组添加元素,它们会在JavaScript代码中显示正确的索引(数字,从零开始):
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" });
使用此JavaScript函数输出时:
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');
}
结果是:
object
0 => 42
1 => foo
所以它有效。除了我想要一个'真正的'数组:)
So it works. Except that I want a 'real' array :)
推荐答案
几乎忘了:
Object.prototype.toString.call(a)
返回[object Array]
好的,这是至关重要的信息。这告诉我们数组实际上是一个数组,它只是由一个 Array
构造函数初始化,其范围与函数测试的范围不同,完全如同虽然您正在一个窗口中测试一个数组,而不是基于浏览器的应用程序中另一个窗口的 Array
构造函数。例如,存在范围问题。
Okay, that's the crucial information. That tells us that the array really is an array, it's just that it's being initialized by an Array
constructor in a different scope than the one that the function is testing for, exactly as though you were testing an array from one window against another window's Array
constructor in a browser-based app. E.g., there's a scope problem.
尝试替换
Object[] fArgs = new Object[]{ new NativeArray(0) };
with
Object[] fArgs = new Object[]{ cx.newArray(scope, 0) };
...以确保正确的数组
使用构造函数。因为您已经直接转到 NativeArray
构造函数,所以绕过了确保其范围正确,因此数组对象的构造函数
是 数组
构造函数,但不是相同的 数组
构造函数作为函数看到的全局对象的构造函数。
...to ensure the correct Array
constructor is used. Because you've gone directly to the NativeArray
constructor, you've bypassed ensuring that its scope is right, and so the array object's constructor
is an Array
constructor, but not the same Array
constructor as the one on the global object the function sees.
这篇关于如何在Rhino中创建一个“真正的”JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!