0

I want to maintain a list of things in javascript. This seems to be a non trivial problem in this language...

var things = []

// for adding:
things[things.length] = thing

// for removing:
delete (things[things.indexOf(thing)])

This kinda works, but I fear the adding is a bug. When a thing that is not at the end of the array gets removed, a following add operation will overwrite an existing element, right? Because length is the number of elements.

How to do the adding correctly? Or is there a better way to do this with plain javascript (no JQuery)?

typ1232
  • 5,535
  • 6
  • 35
  • 51
  • Have a read through all of the [available `Array.prototype` methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). You will find better ways to achieve both of those things. – James Allardice Jun 26 '14 at 14:33
  • 2
    [`push()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) and [`splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). – Sirko Jun 26 '14 at 14:33
  • possible duplicate of [JavaScript Array Delete Elements](http://stackoverflow.com/questions/500606/javascript-array-delete-elements) – tcooc Jun 26 '14 at 14:35
  • This is not a duplicate of the referenced question as it asks about adding and removing elements from an array. – Cameron Tinker Jun 26 '14 at 14:43
  • @JamesAllardice I didn't, sorry. All I found were weird solutions like the one I posted, or someone was even setting elements to 0 for "removing". – typ1232 Jun 26 '14 at 14:47

4 Answers4

1

For adding you want to use push, so things.push(yourThing);

n0wak
  • 76
  • 3
1

I would recommend using push and splice. With push, you don't have to keep track of your last inserted index. Also, with splice, you actually remove the element from the array and you aren't just deleting the reference and making it null.

Something like this would work:

things.push(thing);
things.splice(index, 1);
Cameron Tinker
  • 9,634
  • 10
  • 46
  • 85
-1

I would use a loop.

var index;
var things= [];
for (index = 0; index < things.length; ++index) {
    text += things[index];
}
Izekid
  • 177
  • 6