开发者

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

Where can I find a List class for javascript with add(obj) remove(o开发者_Python百科bj) and contains(obj)?


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.


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


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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜