我试图在属性与我的参数匹配时删除特定对象(此时轮子的名称是"米其林")但我无法使其工作..
我怎么能这样做?
var car = {
type: "Fiat",
model: "500",
color: "White",
wheels: [{
name: "Goodyear",
color: "Red"
}, {
name: "Goodyear",
color: "Yellow"
}, {
name: "Goodyear",
color: "Black"
}, {
name: "Michelin",
color: "Blue"
}]
};
$.each(car.wheels, function() {
if (this.name == "Michelin") {
delete this;
}
})
console.log(car);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 0 :(得分:4)
$.each
方法的回调函数有两个参数:
$.each(car.wheels, function(i,item) {
if (item.name == "Michelin") {
delete car.wheels[i];
}
});
但这 最佳解决方案。通常,delete
运算符用于从对象删除属性。如果你在数组上使用它,删除将删除数组项,但不会重新索引数组或更新其长度。这使它看起来好像是未定义的:
var car = {
type: "Fiat",
model: "500",
color: "White",
wheels: [{
name: "Goodyear",
color: "Red"
}, {
name: "Goodyear",
color: "Yellow"
}, {
name: "Goodyear",
color: "Black"
}, {
name: "Michelin",
color: "Blue"
}]
};
$.each(car.wheels, function(i,item) {
if (item.name == "Michelin") {
delete car.wheels[i];
}
});
console.log(car);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
解决方案是使用filter
方法接受回调提供的函数应用于数组中的每个项目。
var car = {
type: "Fiat",
model: "500",
color: "White",
wheels: [{
name: "Goodyear",
color: "Red"
}, {
name: "Goodyear",
color: "Yellow"
}, {
name: "Goodyear",
color: "Black"
}, {
name: "Michelin",
color: "Blue"
}]
};
car.wheels=car.wheels.filter(function(wheel){
return wheel.name!='Michelin';
});
console.log(car);
&#13;
答案 1 :(得分:1)
使用jQuery grep功能:
var car = {
type: "Fiat",
model: "500",
color: "White",
wheels: [{
name: "Goodyear",
color: "Red"
}, {
name: "Goodyear",
color: "Yellow"
}, {
name: "Goodyear",
color: "Black"
}, {
name: "Michelin",
color: "Blue"
}]
};
car.wheels= $.grep(car.wheels,function(wheel){
return wheel.name!='Michelin';
});
console.log(car);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;