2015-09-05 69 views
3

我有一個JavaScript對象如下:在JavaScript中通過引用刪除數組的項目?

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

我添加obj到一個數組如下:

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

現在我想刪除arr[0]。我只能訪問obj,但我想要刪除obj,然後自動刪除arr[0]

我該怎麼辦這可能嗎?

+1

http://stackoverflow.com/questions/5767325/remove-a-specific-element-from-an-array-in-javascript – Okx

+1

的可能的複製什麼你的意思是隻能訪問'obj'嗎? –

+0

'array.splice'? – skypjack

回答

0

這是不可能的。您必須訪問arr,然後使用delete arr[0]

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