Not quite sure how to phrase this question (I am sure it has been asked before in some form).
My problem is essentially shown below (through some badly written pseudo-javascript code):
var list = []
for (i to somenumber)
list.push(new myObject);
list.foreach(function(item){
if (item.name === 'WhatIAmLookingFor')
item.delete() <--- This needs to remove the object from list
}
So as my amazing code alludes to I want to be able to remove the item from the list by calling a function on an object in the list.
Sorry if this is an ignorant question but I cant figure out how to do this.
Instead of deleting items, use filter
to keep only "good" ones.
var list = [ { name: 'foo' }, { name: 'bar' }, { name: 'removeMe' }, { name: 'baz' } ]; list = list.filter(function(item) { return item.name != 'removeMe' }); document.write(JSON.stringify(list))
To remove an element "inside out", eg element.removeFrom(list)
, you need array.splice
:
obj = function(name) { this.name = name; this.removeFrom = function(lst) { for (var i = 0; i < lst.length; ) { if (lst[i].name == this.name) lst.splice(i, 1); else i++; } } } a = new obj('a'); b = new obj('b'); c = new obj('c'); x = new obj('remove'); list = [a, b, c, x, x, a, b, c, x] x.removeFrom(list) document.write(JSON.stringify(list))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.