【发布时间】:2017-12-17 23:06:33
【问题描述】:
我正在尝试在属性与我的参数匹配时删除特定对象(此处当轮子的名称为“Michelin”时)但我无法使其工作...
我该怎么做?
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>
【问题讨论】:
-
你不能在函数中使用“this”。使用迭代对象。
-
回调函数有 2 个参数。第一个是索引,第二个是迭代对象,用那个。
-
Alexandru 的回答很到位。另外,我建议从不使用
$.each()。这是一个混乱的功能,是零碎发展的。在 Alexandru 的代码中使用.forEach()或更合适的函数,如.filter()。如果您出于某种原因必须使用$.each()(不,真的,不要!)至少不要在回调中使用this。这让事情变得非常混乱。相反,请使用回调的两个命名参数,如提到的 doublesharp。
标签: javascript jquery arrays function