如何在javascript中删除对象的一部分

这是我的代码:

var data = []; $("#btn").click(function(){ total++; data.push({ id : total, "cell": [ "val1", "val2", "val3", ] }); }); 

每次用户点击btn按钮时,我都会向数据对象添加一些值。 现在我的问题在于我如何删除id = X的部分

您可以在位置X使用.splice()

 var data = [{id : total, "cell" : ["val1", "val2", "val3"]}[, ...repeat]; var X = 0; // position to remove data.splice(X,1); 

延期:

 for (var i=data.length-1; 0 < i; i--) { if (data[i].id == X) { data.splice(X,1); break; } } 

只是用
x = {id1: "some value"}
delete x.id1

就是这样

这是另一种想法。 使用id作为对象中的键而不是:

 var data = {}; $("#btn").click(function(){ total++; data[total] = { cell: [ "val1", "val2", "val3" ] }; }); 

然后删除具有该特定ID的对象,您可以执行以下操作:

delete data[id];

要么

data[id] = null;

只是为了它。

这样你就可以消除在那里拥有数组的复杂性。