简体   繁体   中英

How do I call the key of an object but returned as a method, not a string

I'm trying to use a variable for skillName which represents 'Tackle' and i dont want to use userBattlePokemon[0].skills.Tackle because i want my code to be more dynamic for different skills from different objects. But skillName currently represents a string, which means the enemyBattlePokemon[0].health became NaN .

For this instance, is there any way to write it so that skillName returns Tackle which is not a string and can be used in the assignment?

userBattlePokemon = [{
    skills: {
        Tackle: 5,
        LeechSeed: 10
    }
}];

enemyBattlePokemon = [{
    health: 100
}];

let skillName = userBattlePokemon[0].skills[0]

enemyBattlePokemon[0].health = enemyBattlePokemon[0].health - userBattlePokemon[0].skills[0].skillName

Hope It will solve your problem

let key="Tackle";//Leechseed could be a key 
let skillName = userBattlePokemon[0].skills[key]

I'm not completely sure, if I understand your problem, but I would suggest structuring your object like this:

userBattlePokemon = [{
    skills: [{
        name: Tackle,
        attack: 5
    }, {
        name: LeechSeed,
        attack: 10
    }]
}];

This way you can access your skill by an index and still keep a useful name.

enemyBattlePokemon[0].health = enemyBattlePokemon[0].health - userBattlePokemon[0].skills[0].atttack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM