Well splice
works:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the delete
operator on Arrays. delete
will not remove an entry from an Array, it will simply replace it with undefined
.
var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]
But maybe you want something like this?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if( arr[i]
&& arr[i].hasOwnProperty(attr)
&& (arguments.length > 2 && arr[i][attr] === value ) ){
arr.splice(i,1);
}
}
return arr;
}
Just an example below.
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]
removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…