如何从数组中删除对象? 我希望从someArray中删除包含名称Kristian的对象。例如:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

我想实现:

someArray = [{name:"John", lines:"1,19,26,96"}];

当前回答

虽然这可能不适合这种情况,我发现前几天,如果你不需要改变数组的大小,你也可以使用delete关键字从数组中删除一个项目。

var myArray = [1,2,3];

delete myArray[1];

console.log(myArray[1]); //undefined

console.log(myArray.length); //3 - doesn't actually shrink the array down

其他回答

someArray = jQuery.grep(someArray , function (value) {
        return value.name != 'Kristian';
});

虽然这可能不适合这种情况,我发现前几天,如果你不需要改变数组的大小,你也可以使用delete关键字从数组中删除一个项目。

var myArray = [1,2,3];

delete myArray[1];

console.log(myArray[1]); //undefined

console.log(myArray.length); //3 - doesn't actually shrink the array down

最简单的解决方案是创建一个映射,按名称存储每个对象的索引,如下所示:

//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );

//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );

Splice (i, 1),其中i是数组的增量索引,将删除对象。 但是请记住,splice也会重置数组长度,所以要注意'undefined'。用你的例子,如果你删除了“Kristian”,那么在循环中的下一次执行中,i将是2,但someArray将是1的长度,因此,如果你试图删除“John”,你会得到一个“undefined”错误。解决这个问题的一个方法是使用单独的计数器来跟踪要删除的元素的索引。

在你的数组语法中似乎有一个错误,所以假设你的意思是一个数组,而不是一个对象,数组。Splice是你的朋友:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)