我怎樣才能把一個數組的對象通過ID例如:使用javascript從數組中刪除對象?
users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}]
說我想用javascript刪除ID爲「10051」的用戶,我試圖通過互聯網搜索,但沒有找到任何東西?
加我不想使用下劃線!
我怎樣才能把一個數組的對象通過ID例如:使用javascript從數組中刪除對象?
users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}]
說我想用javascript刪除ID爲「10051」的用戶,我試圖通過互聯網搜索,但沒有找到任何東西?
加我不想使用下劃線!
加我不想使用下劃線!
這種本地方法是.filter()
:
var removeId = "4567";
users = users.filter(function (user) { return user.id !== removeId; });
注意,它需要發動機是ES5-compatible(或polyfill)。
for (var i = 0; i < users.length; ++i)
{
if (users[i].id == "10051")
{
users[i].splice(i--, 1);
}
}
您可以使用.filter
數組的方法。
users = users.filter(function(el) {return el.id !== '10051'});
var users= [{id:"10051", name:"Mike Coder"},{id:"4567", name:"Jhon Second"}];
/* users.length= 2 */
function removebyProperty(prop, val, multiple){
for(var i= 0, L= this.length;i<L;i++){
if(i in this && this[i][prop]=== val){
this.splice(i, 1);
if(!multiple) i= L;
}
}
return this.length;
}
removebyProperty.call(用戶, 'ID', 「10051」);
返回值:(數字)1
你得到答案瞭如何構建一個新的,過濾陣列,但你的問題似乎問如何從目前的陣列中刪除。你需要哪一個? – Pokey 2013-04-22 00:42:08