tags:

views:

129

answers:

1

I'm using Google Web Tools, and have a JsArray, which I'm populating with data from JSON. I'm able to modify items within the array and add items to it, but I can't figure out how to remove an item from it. I'm looking for something similar to the pop() method in JavaScript.

I can add an item to the array by using the set(index,value) method with an index that's out of the array's range, so I tried using set(index,null) to remove it, but the array still has the item, it's just null. (i.e. the array's length is unchanged.)

I'm currently using a hacky method whereby I create a new array, and copy all of the elements except the last one from the old to the new, but I'm hoping I don't have to live with that, because it's ugly.

private final JsArray<JsArrayInteger> popItemFromArray(
     JsArray<JsArrayInteger> oldArray) {
    // the createEmpty...  method is a native method which returns eval("[]")
    JsArray<JsArrayInteger> newArray = createEmptyIntIntArray();

    for (int i = 0; i < oldArray.length() - 1; i++) {
     newArray.set(i, oldArray.get(i));
    }

    return newArray;
}
+1  A: 

There's no pop(), but there's... shift() :)

Either that or extend the JsArray class, something like this (not tested, but you should get the idea):

public class JsArrayPop<T extends JavaScriptObject> extends JsArray<T> {

  protected JsArrayPop() {
  }

  public final native T pop() /*-{
    return this.pop();
  }-*/;

}
Igor Klimer
I don't see a `shift()` method--unless that was a joke that went over my head--but extending the `JsArray` class does the trick.
sernaferna
Maybe that's because I'm using my own 2.0-SNAPSHOT build, but I'm sure that my version of `com.google.gwt.core.client.JsArray<T>` has a `shift()` method (of course, it's just as simple as the `pop()` method, so you can add it easily).
Igor Klimer