0

I have an Arc and a Line class setup in JavaScript for managing a lot of arcs and lines of a canvas. I plan on having an array for managing them and I imagine needing to add or remove elements like an ArrayList.

After Googling around, it seems like JavaScript doesn't directly support this, and that the best case is making an element null when you want to remove it. If I am wrong please let me know. If I am not wrong, what would be the best thing to do? Should I make a function along these lines? (The example just uses integers to make things simple)

var example = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
example[2] = null;
example[7] = null;

example = removeNulls(example);
function removeNulls(inArr) {
    var newArr = new Array();
    for (var i = 0; i < inArr.length; i++) if (inArr[i] != null) newArr.push(inArr[i]);
    return newArr;
}
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
asimes
  • 5,749
  • 5
  • 39
  • 76
  • Check out the `splice` method. – Raymond Chen Mar 03 '13 at 00:18
  • Just an advide - don't use the `Array` constructor if you want to specify the elements. Use it only when you want to define its length, or else use `[1, 2, 3...]`. Remember that Javascript isn't Java. – MaxArt Mar 03 '13 at 00:20
  • Knowing its length would be useful, what is wrong with using it? – asimes Mar 03 '13 at 00:21
  • Just google JavaScript array https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array – Christophe Mar 03 '13 at 00:27
  • possible duplicate of [JavaScript Array Delete Elements](http://stackoverflow.com/questions/500606/javascript-array-delete-elements) – Raymond Chen Mar 03 '13 at 13:43

1 Answers1

2

You can use .splice on the array.

Ven
  • 19,015
  • 2
  • 41
  • 61