我有一个如下的JavaScript对象:
obj = {
a: 'a',
b: 'b',
}
我按照以下方式将obj
添加到数组中:
arr = [];
arr.push(obj);
现在我想删除
arr[0]
。我只能访问obj
,但我想删除obj
然后自动删除arr[0]
。如何做到这一点,或者是否可能?
我有一个如下的JavaScript对象:
obj = {
a: 'a',
b: 'b',
}
我按照以下方式将obj
添加到数组中:
arr = [];
arr.push(obj);
arr[0]
。我只能访问obj
,但我想删除obj
然后自动删除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);
这是不可能的。你必须访问 arr
,然后使用 delete arr[0]
。
obj
吗? - Neo