9

I need to convert values of type T into JsArray.

For example, I have String1, String2 .... Stringn. I need to convert these Strings into JsArray string.

How can I implement this?

Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21
Gnik
  • 7,120
  • 20
  • 79
  • 129

3 Answers3

21

You don't have much choices: creating a JsArrayString and adding to it, or using JSNI.

JsArrayString arr = JavaScriptObject.createArray().cast();
arr.push(str1);
arr.push(str2);
arr.push(str3);

or

static native JsArrayString asJsArray(String str1, String str2, String str3) /*-{
  return [str1, str2, str3];
}-*/;

Obviously, the latter doesn't scale, while being faster.

It really depends what exactly you need to do.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
4

Use JsArrayUtils like this:

JsArray<String> arr = JsArrayUtils.readOnlyJsArray(new String[] { string1, string2 });

Take a look at the javadoc:

com.google.gwt.core.client.JsArrayUtils

Utility class for manipulating JS arrays. These methods are not on other JavaScriptObject subclasses, such as JsArray, because adding new methods might break existing subtypes.

Italo Borssatto
  • 15,044
  • 7
  • 62
  • 88
1

Using generics, could do it like this:

public <T extends JavaScriptObject> JsArray<T> createGenericArray(T... objects) {
    JsArray<T> array = JavaScriptObject.createArray().cast();

    for (T object : objects) {
        array.push(object);
    }

    return array;
}

Obviously, String doesn't extend JavaScriptObject. You'd need to have overloads to account for primitive types. (Or, less safely, you could remove the bounds of T to allow for arbitrary types. You'd need to be much more careful if you were to do so.)

Chris Cashwell
  • 22,308
  • 13
  • 63
  • 94