gpt4 book ai didi

Javascript:如何根据项属性值删除数组项(JSON 对象)?

转载 作者:行者123 更新时间:2023-11-30 07:48:09 25 4
gpt4 key购买 nike

像这样:

var arr = [  
{ name: "robin", age: 19 },
{ name: "tom", age: 29 },
{ name: "test", age: 39 }
];

我想像这样删除数组项(数组原型(prototype)方法):

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 性能合理,并在可用的情况下使用 Array 对象的内置 filter 方法,因此该位可能是美好的。我要更改的位是将过滤后的项目复制回原始数组的位:

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
};

关于Javascript:如何根据项属性值删除数组项(JSON 对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com