JavaScript Java Bridge API provides JSArray class that represents a wrapper for JavaScript array object. If JavaScript returns an array to Java code, the array value will be represented in Java code as JSArray object. For example:(JavaScript Java Bridge API提供了JSArray类,该类表示JavaScript数组对象的包装。如果JavaScript将数组返回给Java代码,则数组值将在Java代码中表示为JSArray对象。例如:)

JSValue result = browser.executeJavaScriptAndReturnValue("[1, 'test', 3]");
JSArray array = result.asArray();

In the example above JavaScript code returns an array with three items (1, 'test', 3) to Java code. The JSValue can be cast to JSArray type to work with JavaScript array. Using JSArray class you can get length of the array, access array items, and modify JavaScript array with new items.(在上面的示例中,JavaScript代码将一个包含三个项目(1,“ test”,3)的数组返回给Java代码。可以将JSValue强制转换为JSArray类型以与JavaScript数组一起使用。使用JSArray类,您可以获取数组的长度,访问数组项以及使用新项修改JavaScript数组。)


Please note that JSArray points to existing JavaScript array on the loaded web page. If the web page was reloaded or unloaded, JSArray object will point to an invalid JavaScript array that was disposed during unloading the web page. If you try to use this JSArray instance, the IllegalStateException error will be thrown.(请注意,JSArray指向已加载网页上的现有JavaScript数组。如果重新加载或卸载了Web页面,则JSArray对象将指向在卸载Web页面时释放的无效JavaScript数组。如果尝试使用此JSArray实例,则将引发IllegalStateException错误。)


Getting Array Length(获取数组长度)

To get the array length use the JSArray.length() method. For example:(要获取数组长度,请使用JSArray.length()方法。例如:)

JSValue result = browser.executeJavaScriptAndReturnValue("[1, 'test', 3]");
JSArray array = result.asArray();
assert array.length() == 3;

 

Getting Array Items(获取数组项)

To access the array item at specific index use the JSArray.get(int index) method. The index cannot be negative. It can be more than array length. In this case the "undefined" value will be returned. For example:(要访问特定索引处的数组项,请使用JSArray.get(int index)方法。索引不能为负。它可以大于数组长度。在这种情况下,将返回“ undefined”值。例如:)

assert array.get(0).asNumber().getInteger() == 1;
assert array.get(1).getStringValue().equals("test");
assert array.get(2).asNumber().getInteger() == 3;
assert array.get(100).isUndefined();


Setting Array Items(设置阵列项目)

You can modify existing array items or add new items using the JSArray.set(int index, Object value) method. The method returns a boolean value that indicates whether the given value was successfully inserted into the array. You can insert new values at the index more than array length. In this case the size of the array will be increased, the new item will be inserted at the given position, all items between the latest valid array element and the new one will be filled with "undefined" values.(您可以使用JSArray.set(int index,Object value)方法修改现有数组项或添加新项。该方法返回一个布尔值,该布尔值指示给定值是否已成功插入到数组中。您可以在索引处插入比数组长度更多的新值。在这种情况下,数组的大小将增加,新项目将插入到给定位置,最新有效数组元素和新项目之间的所有项目都将填充“ undefined”值。)

assert array.set(0, "String value");
assert array.set(100, 123);