我有一个javascript对象如下:
obj = {
a: 'a',
b: 'b',
}
我将obj
添加到数组中,如下所示:
arr = [];
arr.push(obj);
现在我要删除arr[0]
。我只能访问obj
,但我想删除obj
,然后自动删除arr[0]
。
我该怎么做,或者有可能吗?
答案 0 :(得分:1)
保存插入对象的索引:
arr.push(obj);
var index = arr.length - 1;
然后使用保存的索引向对象添加一个方法以将其从数组中删除:
obj.remove = function () {
delete arr[index];
};
然后,代码中arr
超出范围的其他地方,只需执行
obj.remove();
注意:这将在您的对象所在的位置在数组中留下一个洞,它不会重新组织数组,左右移动元素以填充孔。如果您不想留下漏洞,请不要使用数组,而应使用链接列表。
答案 1 :(得分:1)
您可以将列表附加到对象本身,然后以这种方式访问列表以删除对象?这有点乱,理想情况下,您可以找到重组代码的方法,但是这些事情发生了!所以这可能会有所帮助:
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);
答案 2 :(得分:0)
这是不可能的。您必须访问arr
,然后使用delete arr[0]
。