像这样:
var arr = [
{ name: "robin", age: 19 },
{ name: "tom", age: 29 },
{ name: "test", age: 39 }
];
我想删除这样的数组项(数组原型方法):
arr.remove("name", "test"); // remove by name
arr.remove("age", "29"); // remove by age
目前,我通过这种方法(使用 jQuery)做到这一点:
Array.prototype.remove = function(name, value) {
array = this;
var rest = $.grep(this, function(item){
return (item[name] != value);
});
array.length = rest.length;
$.each(rest, function(n, obj) {
array[n] = obj;
});
};
但我认为该解决方案存在一些性能问题,那么有什么好主意吗?
我希望 jQuery 的名字很奇怪grep
将具有合理的性能并使用内置的filter
Array 对象的方法(如果可用),因此该位可能没问题。我要更改的位是将过滤后的项目复制回原始数组的位:
Array.prototype.remove = function(name, value) {
var rest = $.grep(this, function(item){
return (item[name] !== value); // <- You may or may not want strict equality
});
this.length = 0;
this.push.apply(this, rest);
return this; // <- This seems like a jQuery-ish thing to do but is optional
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)