初学者可能是一个非常明显的问题:
如果我有以下数组...
var arr =
[
{id: 1, item: "something", description: "something something"},
{id: 2, item: "something else", description: "something different"},
{id: 3, item: "something more", description: "more than something"}
]
...并希望通过调用id删除其中的特定对象(在这种情况下,通过单击给定相应ID的div)...
var thisItem = $(this).attr("id");
...我可以在不使用for循环来匹配arr[i]
和thisItem
的情况下执行此操作吗?如果是这样,怎么样?我将拥有一个大阵列,因此运行for循环似乎非常沉重。
谢谢!
答案 0 :(得分:3)
您可以使用Array.filter过滤任何数组。此方法将过滤函数作为其参数,并在原始数组的每个元素上运行它。如果此函数的返回值为false
,则该元素将从返回的新数组中过滤掉。原始数组不受影响。
var arr =
[
{id: 1, item: "something", description: "something something"},
{id: 2, item: "something else", description: "something different"},
{id: 3, item: "something more", description: "more than something"}
];
function filterArray( id ){
return arr.filter(function(item){
return item.id != id;
});//filter
}//filterArray()
console.log( filterArray(2) );
答案 1 :(得分:2)
您可以使用JQuery的grep
arr = jQuery.grep(arr, function(value) {
return value.id != id;
});
答案 2 :(得分:0)
普通JS解决方案:
var arr = [{
id: 1,
item: "something",
description: "something something"
}, {
id: 2,
item: "something else",
description: "something different"
}, {
id: 3,
item: "something more",
description: "more than something"
}];
var filtered = filterArrayByElemId(arr, 2);
console.log(filtered);
function filterArrayByElemId(arr, id) {
return arr.filter(function(item) {
return item.id != id;
});
}