简体   繁体   中英

Javascript enum with multiple values and value types

I'm trying to make a system which reads Dota 2 hero data, in this system I have to store a lot of data about each hero (strength gain, int gain, agility gain)(float) and also what their primary attribute is.

This is what I have so far:

const Heroes = {
Abaddon: 'Strength',
Alchemist: 'Strength',
AncientApparition: 'Intelligence',
AntiMage: 'Agility',
ArcWarden:'Agility',
Axe:'Strength',

}

tried this:

const Heroes = {
Abaddon: ('Strength','3.4', '2.4', '1.8', true),
Alchemist: ('Strength','2.8', '2.3', '1.6', true),
}
console.log(Heroes.Abaddon)

The output was just the last value (true)

You could get creative and use Enums like Java uses them, for more than a way to rename integers like many other languages. Or you could simply use a standard JavaScript object like this:

const Heroes = {
  Abaddon: {
     primaryAttribute: 'Strength',
     attributeGains: {
        strength: 3.4,
        intelligence: 2.4,
        agility: 1.8
     }
  },
  Alchemist: {
     primaryAttribute: 'Strength',
     attributeGains: {
        strength: 2.8,
        intelligence: 2.3,
        agility: 1.6
     }
  }
};

Accessing the values are as simple as you would expect.

console.log(Heroes.Abaddon.primaryAttribute);
console.log(Heroes.Alchemist.attributeGains.agility);

I'm not sure why you are in need of an Enum specifically, but in the end, you will be making a complex but standard JavaScript object.

You can't do this with JavaScript. The parentheses are just extras. Try using arrays:

const Heroes = {
    Abaddon: ['Strength','3.4', '2.4', '1.8', true],
    Alchemist: ['Strength','2.8', '2.3', '1.6', true],
}
console.log(Heroes.Abaddon)

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