我有一个JavaScript对象如下:在JavaScript中通过引用删除数组的项目?
obj = {
a: 'a',
b: 'b',
}
我添加obj
到一个数组如下:
arr = [];
arr.push(obj);
现在我想删除arr[0]
。我只能访问obj
,但我想要删除obj
,然后自动删除arr[0]
。
我该怎么办或这可能吗?
我有一个JavaScript对象如下:在JavaScript中通过引用删除数组的项目?
obj = {
a: 'a',
b: 'b',
}
我添加obj
到一个数组如下:
arr = [];
arr.push(obj);
现在我想删除arr[0]
。我只能访问obj
,但我想要删除obj
,然后自动删除arr[0]
。
我该怎么办或这可能吗?
这是不可能的。您必须访问arr
,然后使用delete arr[0]
。
保存在其中的物体被插入的索引:
arr.push(obj);
var index = arr.length - 1;
,然后添加方法将对象从数组中删除它,使用所保存的索引:
obj.remove = function() {
delete arr[index];
};
然后,代码中的其他地方arr
已经超出范围,只要做
obj.remove();
注意:这会在你的对象所在的地方留下一个洞,它不会重新组织阵列,向左和向右移动元素来填充洞。如果您不想留下漏洞,请不要使用数组,而应使用链接列表。
您可以将列表附加到对象本身,然后以这种方式访问列表以删除对象?这有点乱,理想情况下你会找到一种重组代码的方式,但是嘿,这些事情发生了!所以这可能帮助:
http://jsfiddle.net/dk79mb3x/1/
// This function, and returning the obj, is not strictly
// necessary. I am doing it to achieve a state where the obj is
// in scope, but the list is not.
function defineStuff() {
var list = [];
var obj = {
a: 'a',
b: 'b',
// These two are the useful bits!
container: list,
index: list.length
// We can only delete this once, if you try a second time, the
// index will be incorrect!
deleted: false;
};
list.push(obj);
return obj;
}
obj = defineStuff();
// Note that the list is no longer in scope
console.log(typeof list);
// But we know it has one item in it... this should log '1'
console.log(obj.container.length);
// Now we can delete via the object like this...
if (!obj.deleted)
obj.container.splice(obj.index, 1);
// (You could work around this index issue and remove the .deleted flag by
// instead searching the list for something that matches the object. If you
// have an object.key, for example, that would work well.)
// Is it now empty? This should log '0'
console.log(obj.container.length);
http://stackoverflow.com/questions/5767325/remove-a-specific-element-from-an-array-in-javascript – Okx
的可能的复制什么你的意思是只能访问'obj'吗? –
'array.splice'? – skypjack