如何在JavaScript中通过引用删除数组的元素?

3

我有一个如下的JavaScript对象:

obj = {
   a: 'a',
   b: 'b',
}

我按照以下方式将obj添加到数组中:

arr = [];
arr.push(obj);

现在我想删除arr[0]。我只能访问obj,但我想删除obj然后自动删除arr[0]
如何做到这一点,或者是否可能?

1
可能是 https://dev59.com/CG025IYBdhLWcg3w1ZoL 的重复问题。 - Okx
1
你的意思是只能访问 obj 吗? - Neo
1
@Okx 这不是重复内容。我认为 OP 的意思是在他想要从数组中删除 obj 的时候,该数组已经超出了作用域,这并不是你链接的那个问题所回答的情况。 - jrsala
如果您只想从最后一个数组中删除obj内容,只需编写arr.pop()。 - Maytham Fahmi
1
OP很可能想通过删除“obj”来间接编辑数组。不可能,参见答案。 - Vidul
是的,我做不到,这是不可能的。 - Morteza Malvandi
3个回答

1

保存对象插入的索引:

arr.push(obj);
var index = arr.length - 1;

然后在对象中添加一个方法,使用保存的索引从数组中删除它:

obj.remove = function () {
    delete arr[index];
};

然后,在你的代码中,当arr超出作用域时,只需执行以下操作。
obj.remove();

注意:这将在您的数组中留下一个空洞,即您的对象所在的位置,它不会重新组织数组,左右移动元素以填补空洞。如果您不想留下空洞,请不要使用数组,而是使用链接列表。

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

0

这是不可能的。你必须访问 arr,然后使用 delete arr[0]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接