gpt4 book ai didi

javascript - 如何删除数组内对象的值

转载 作者:行者123 更新时间:2023-12-03 19:39:50 27 4
gpt4 key购买 nike

这怎么行不通?一切对我来说似乎都是正确的。我错过了什么吗?

编写一个名为 removePartyKillers 的函数,它接收一个像“播放列表”这样的数组(见下文)并返回该播放列表的副本,其中任何歌曲超过 8 分钟已被删除。您可以放心地假设播放列表是一个对象数组。每个对象都有属性 title、artist 和 durationInSeconds。

var awesomePlaylist = [
{
title: "Hay Day",
artist: "Robo-Crop",
durationInSeconds: 378
}, {
title: "10,000 Pounds",
artist: "L-Ton Jonn",
durationInSeconds: 498,
}, {
title: "Caesar's Salad",
artist: "DJ Dinner Julius",
durationInSeconds: 600,
}, {
title: "The British Are On Their Way",
artist: "Raul Pevere",
durationInSeconds: 1095,
}, {
title: "13th",
artist: "The Doctors",
durationInSeconds: 185,
}
];

function removePartyKillers(arr) {
var copy = arr.slice();
for (var key of copy) {
for (var key2 in key) {
if (key2['durationInSeconds'] > (60 * 8)) {
delete key2;
}
}
}
return copy;
}

console.log(removePartyKillers(awesomePlaylist));
/* Results:
{
title: "Hay Day",
artist: "Robo-Crop",
durationInSeconds: 378
}, {
title: "13th",
artist: "The Doctors",
durationInSeconds: 185,
}
]
*/

最佳答案

我认为 .filter() 在这种情况下很有用。

注意: awesomePlaylist 本身不是一个对象(关联数组)而是一个数组;因此,您需要操作数组。 delete 操作对象中的属性。

let awesomePlaylist = [{
title: "Hay Day",
artist: "Robo-Crop",
durationInSeconds: 378
}, {
title: "10,000 Pounds",
artist: "L-Ton Jonn",
durationInSeconds: 498,
}, {
title: "Caesar's Salad",
artist: "DJ Dinner Julius",
durationInSeconds: 600,
}, {
title: "The British Are On Their Way",
artist: "Raul Pevere",
durationInSeconds: 1095,
}, {
title: "13th",
artist: "The Doctors",
durationInSeconds: 185,
}];

function removePartyKillers(arr) {
return arr.filter(song => song.durationInSeconds <= 8*60)
}

console.log(removePartyKillers(awesomePlaylist));

关于javascript - 如何删除数组内对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66485333/

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