gpt4 book ai didi

javascript - .filter() 方法返回一个空数组

转载 作者:行者123 更新时间:2023-11-30 19:43:57 25 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 的 filter() 方法返回一个对象数组,其中的对象具有特定值。在我的场景中,用户可以有名字、姓氏和附加的多个字符。

我正在尝试使用 filter() 返回任何具有至少 100 或更多金币的字符的对象,但它返回一个空数组。这是我写的:

var users = [{
firstname: 'Owen',
lastname: 'Wilson',
characters: [{
race: 'dwarf',
level: 80,
gold: 150
},
{
race: 'dark elf',
level: 75,
gold: 50
},
{
race: 'human',
level: 70,
gold: 75
}
]
},

{
firstname: 'Vince',
lastname: 'Vaughan',
characters: [{
race: 'dwarf',
level: 80,
gold: 90
},
{
race: 'dark elf',
level: 75,
gold: 50
},
{
race: 'human',
level: 70,
gold: 75
}
]
},

{
firstname: 'Ben',
lastname: 'Stiller',
characters: [{
race: 'dwarf',
level: 80,
gold: 200
},
{
race: 'dark elf',
level: 75,
gold: 50
},
{
race: 'human',
level: 70,
gold: 75
}
]
}

];
var minimumGold = element => element.characters.gold >= 100;
var usersWithLotsOfGold = users.filter(minimumGold);
console.log(usersWithLotsOfGold);
// Expected objects [0] and [2]

最佳答案

您需要检查characters 数组中的每个字符。一种方法是使用 Array.prototype.some()像这样:

const users = [{firstname:'Owen',lastname:'Wilson',characters:[{race:'dwarf',level:80,gold:150},{race:'dark elf',level:75,gold:50},{race:'human',level:70,gold:75}]},{firstname:'Vince',lastname:'Vaughan',characters:[{race:'dwarf',level:80,gold:90},{race:'dark elf',level:75,gold:50},{race:'human',level:70,gold:75}]},{firstname:'Ben',lastname:'Stiller',characters:[{race:'dwarf',level:80,gold:200},{race:'dark elf',level:75,gold:50},{race:'human',level:70,gold:75}]}];
const minimumGold = element => element.characters.some(
character => character.gold >= 100
);
const usersWithLotsOfGold = users.filter(minimumGold);

console.log(usersWithLotsOfGold);

关于javascript - .filter() 方法返回一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113221/

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