[英]What's the fastest way to remove an object from an array that has a specific property?
How can I remove: 如何删除:
var arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
the object in the array with b
set to 2? b
设置为2的数组中的对象?
arr = arr.filter(function( a ) {
return a.b !== 2;
});
This will only work for IE9+ 这仅适用于IE9 +
I think the fastest way to do that would be a for loop, correct me if I'm wrong... 我认为最快的方法是for循环,如果我写错了,请纠正我...
var arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
for(var i=0; i<arr.length; i++) {
if(arr[i].b==2) { arr.splice(i,1); }
}
According to jsperf the fastest way to delete an array element is to use delete array[index]
. 根据jsperf的说法,删除数组元素的最快方法是使用
delete array[index]
。 Source: http://jsperf.com/object-delete-vs-array-splice-vs-array-delete 资料来源: http : //jsperf.com/object-delete-vs-array-splice-vs-array-delete
A solution could be this: http://jsfiddle.net/no20bv5o/3/ 解决方案可能是这样: http : //jsfiddle.net/no20bv5o/3/
But because of the overhead in the for loop and the second array it is slower as the before mentioned arr.filter()
as shown by this jsperf: http://jsperf.com/filter-array-by-element-attribute 但是由于for循环和第二个数组的开销,它比前面提到的
arr.filter()
慢,如下面的arr.filter()
所示: http ://jsperf.com/filter-array-by-element-attribute
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.