例如我有这个数组
var array1 = [{ uid=24433357, first_name="fname", last_name="lname", ...},
{ uid=4821888, first_name="fname", last_name="lname", ...},
{ uid=677614, first_name="fname", last_name="lname", ...},
{ uid=4789723, first_name="fname", last_name="lname", ...},
{ uid=444464, first_name="fname", last_name="lname", ...},
{ uid=767687867, first_name="fname", last_name="lname", ...}]
我想从array1中删除元素,其中uid = x
我不知道怎么做?
对于普通数组我知道这个方法
array1.splice(index, count)
答案 0 :(得分:3)
首先修复你的对象,语法都错了。请参阅下文,然后使用Array#filter函数按uid
var array1 = [{ uid:24433357, first_name:"fname", last_name:"lname"},
{ uid:4821888, first_name:"fname", last_name:"lname"},
{ uid:677614, first_name:"fname", last_name:"lname"},
{ uid:4789723, first_name:"fname", last_name:"lname"},
{ uid:444464, first_name:"fname", last_name:"lname"},
{ uid:767687867, first_name:"fname", last_name:"lname"}];
ES5 不适合旧浏览器
array1 = array1.filter(function(o){
return o.uid !== 24433357
});
经典方式与旧浏览器兼容
for (var i = 0; i < array1.length; i++) {
if (array1[i].uid === 24433357) {
array1.splice(i, 1);
}
}
console.log(array1);
答案 1 :(得分:1)
for(var i = array1.length-1; i--;){
if (array1.uid[i] === "x") array1.splice(i, 1);
}