从 JavaScript 数组中删除对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11026448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:06:14  来源:igfitidea点击:

Remove object from a JavaScript Array?

javascriptarraysobject

提问by Messi

Possible Duplicate:
Remove specific element from a javascript array?

可能的重复:
从 javascript 数组中删除特定元素?

Specifically I have an array as follows:

具体来说,我有一个数组如下:

var arr = [
    {url: 'link 1'},
    {url: 'link 2'},
    {url: 'link 3'}
];

Now you want to remove valuable element url "link 2" and after removing the only arrays as follows:

现在您要删除有价值的元素 url "link 2" 并删除唯一的数组,如下所示:

arr = [
    {url: 'link 1'},
    {url: 'link 3'}
];

So who can help me this problem? Thanks a lot

那么谁能帮我解决这个问题?非常感谢

回答by xdazz

You could do a filter.

你可以做一个过滤器。

var arr = [
  {url: "link 1"},
  {url: "link 2"},
  {url: "link 3"}
];

arr = arr.filter(function(el){
  return el.url !== "link 2";
});

PS:Array.filtermethod is mplemented in JavaScript 1.6, supported by most modern browsers, If for supporting the old browser, you could write your own one.

PS:Array.filter方法是在JavaScript 1.6中实现的,大多数现代浏览器都支持,如果要支持旧浏览器,你可以自己写一个。

回答by tjscience

Use the splice function to remove an element in an array:

使用 splice 函数删除数组中的元素:

arr.splice(1, 1);

If you would like to remove an element of the array without knowing the index based on an elements property, you will have to iterate over the array and each property of each element:

如果您想在不知道基于元素属性的索引的情况下删除数组的元素,则必须遍历数组和每个元素的每个属性:

for(var a = 0; a < arr.length; a++) {
    for(var b in arr[a]) {
        if(arr[a][b] === 'link 2') {
            arr.splice(a, 1);
            a--;
            break;
        }
    }
}