2

Where can I find a List class for javascript with add(obj) remove(obj) and contains(obj)?

The Student
  • 26,271
  • 66
  • 155
  • 257

4 Answers4

2

you can already use push instead of add and pop instead of remove.

How do I check if an array includes an object in JavaScript? contains an answer for how to do contains.

Community
  • 1
  • 1
stevebot
  • 22,431
  • 27
  • 117
  • 179
2

You could write some simple array extensions:

Array.prototype.add = function (obj) {
    if (this && this.length)
       this.push(obj);
};

[1, 2, 3].add(4);

... etc

Josiah Ruddell
  • 29,337
  • 8
  • 63
  • 67
1

Those aren't hard features to implement. I would simply create my own custom type that inherited from Array and added the two additional methods you'd like (since you can already use push to add items).

Justin Niessner
  • 236,029
  • 38
  • 403
  • 530
1

You can just use the native javascript's arrays

var arr = [];
arr.push(5); // add(obj)
arr.indexOf(5); // returns the index in the array or -1 if not found -> contains(obj)

For removing, you can use arr.pop() to remove last element or arr.shift() to remove the first element.

More on javascript's arrays - http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Radoslav Georgiev
  • 1,356
  • 8
  • 15