gpt4 book ai didi

javascript - 如何删除循环内嵌套的 JS 对象?

转载 作者:行者123 更新时间:2023-11-29 16:41:45 24 4
gpt4 key购买 nike

当属性与我的参数匹配时(此处当轮子的名称是“米其林”时),我试图删除特定对象,但我无法使其工作......

我该怎么做?

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>

最佳答案

$.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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

解决方案是使用 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);

关于javascript - 如何删除循环内嵌套的 JS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45075997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com