2017-09-29 68 views
0

为什么数组中没有定义?我如何删除对象?如何删除对象?

arr = [ 
 
    {id:1,name:'aaa'}, 
 
    {id:2,name:'bbb'}, 
 
    {id:3,name:'ccc'} 
 
]; 
 

 
for(var item in arr){ 
 
    if(arr.hasOwnProperty(item)){ 
 
    if(arr[item].id === 2){ 
 
     delete(arr[item]); 
 
     continue; 
 
    } 
 
    } 
 
} 
 

 
console.log(arr);

回答

1

因为delete不编索引。从文档

当您删除数组元素时,数组长度不受影响。 这适用即使你删除的磁盘阵列

的最后一个元素对于清除你需要使用Array#splice功能,通过索引中删除。首先使用Array#findIndex找到索引,然后传递给拼接函数。

arr = [ 
 
    {id:1,name:'aaa'}, 
 
    {id:2,name:'bbb'}, 
 
    {id:3,name:'ccc'} 
 
]; 
 

 
const index = arr.findIndex(item => item.id === 2); 
 
arr.splice(index, 1); 
 
console.log(arr);

0

您需要修改arr这是objects.The的阵列delete运营商从对象中删除一个给定的属性,你的情况,你需要的元素删除对象

后移

var arr = [{ 
 
    id: 1, 
 
    name: 'aaa' 
 
    }, 
 
    { 
 
    id: 2, 
 
    name: 'bbb' 
 
    }, 
 
    { 
 
    id: 3, 
 
    name: 'ccc' 
 
    } 
 
]; 
 
// iterating the object 
 
arr.forEach(function(item, index) { 
 
    //checking if id === 2, if it is 2 using splice 
 
//method to remove element from that index, & shift by one element 
 
    if (item.id === 2) { 
 
    arr.splice(index, 1) 
 
    } 
 
}) 
 

 
console.log(arr);

2

希望这是你正在尝试做的: -

var arr = [ 
 
    {id:1,name:'aaa'}, 
 
    {id:2,name:'bbb'}, 
 
    {id:3,name:'ccc'} 
 
]; 
 

 

 
arr = arr.filter(function(item){ 
 
    return item.id != 2; 
 
}); 
 

 
console.log(arr)