如何根据数组的值进行过滤
2020-05-09
118
我正在创建一个《王国之心》角色目录,我有一个关于如何过滤它们的问题
首先,我创建了构造类来制作角色和游戏
class character {
constructor(name, gender, alive, race, description,debut, seriesAppearance) {
this.name = name;
this.gender = gender;
this.alive = alive;
this.description = description;
this.race = race
this.debut = debut;
this.seriesAppearance = seriesAppearance;
}
}
class serie {
constructor(name, year, chronology) {
this.name = name;
this.year = year;
this.chronology = chronology;
}
}
然后,我创建了角色和游戏本身
let kh1 = new serie('Kingdom Hearts', '2002', '1')
let khcom = new serie('Kingdom Hearts: Chains of Memories', '2004', '2')
let kh2 = new serie('Kingdom Hearts 2', '2005', '3')
let sora = new character('Sora', 'Male', true, 'Human', 'The Keyblade Master and the protagonist', kh1.name, `${kh1.name}, ${khcom.name} and ${kh2.name}`)
let kairi = new character('Kairi', 'Female', true, 'Human', 'Sora and Riku lost friend', kh1.name, `${kh1.name} and ${kh2.name}`)
let riku = new character('Riku', 'Male', true, 'Human', 'Sasuke of Kingdom Hearts', kh1.name, `${kh1.name} and ${khcom.name}`)
let larxene = new character('Larxene', 'Female', true, 'Nobody', 'Blonde girl who has electrical powers', khcom.name, `${khcom.name} and ${kh2.name}`)
let axel = new character('Axel', 'Male', true, 'Nobody', 'Man with red hair with fire powers', khcom.name, `${khcom.name} and ${kh2.name}`)
let marluxia = new character('Marluxia', 'Male', true, 'Nobody', 'Pink haired man with a scrythe', khcom.name, khcom.name)
let lexaeus = new character('Lexaeus', 'Male', true, 'Nobody', 'Strong guy who has powers to control the land', khcom.name, `${khcom.name} and ${kh2.name}`)
let vexen = new character('Vexen', 'Male', false, 'Nobody', 'Scientist who created the Riku´s replica', khcom.name, khcom.name)
let replicaRiku = new character('Riku Replica', 'Male', true, 'Replica of the riku that only thinks about protecting Namine', khcom.name, khcom.name)
let namine = new character('Namine', 'Female', true, 'Human', ' Blonde girl who controls people´s memories', khcom.name, khcom.name)
let ansem = new character('Ansem', 'Male', true, 'Nobody', 'Enemy who controlled riku´s mind', kh1.name, kh1.name)
然后,我创建了数组来组织每种类型的角色,以及一个包含所有角色的通用数组
let series = [kh1, kh2, khcom]
let heroes = [sora, kairi, namine]
let enemies = [larxene, axel, marluxia, lexaeus, vexen, replicaRiku, ansem]
let ambiguous = [riku]
let characters = [heroes, enemies, ambiguous]
现在,我想创建一个过滤器,可以返回所有活着的角色、人类或男性的名称,因此我仅对人类创建了这个测试函数,但没有成功
function human(race) {
if (this.race == 'Human') {
return this.name
}
}
var humans = heroes.filter(human);
如何使此功能正常工作?
更新
此方法适用于简单数组
function human(hero) {
return hero.race === 'Human';
}
const humanNames = heroes.filter(human).map(human => human.name);
如何使其在角色数组(一个数组)?
1个回答
Array.prototype.filter
将一个项目传递给回调,仅保留那些返回真值的元素。您正在寻找以下回调函数:
function human(hero) {
return hero.race === 'Human';
}
如果您只对名称感兴趣,您可以将您的英雄映射到名称数组:
const humanNames = heroes.filter(human).map(human => human.name);
Robo Robok
2020-05-09