JS Object值取决于其他对象值

时间:2018-03-02 23:58:03

标签: javascript arrays object nested var

我正在用Javascript进行宠物小精灵战斗。我为口袋妖怪和动作做了对象。即

var party1 = prompt("Pick BULBASAUR, SQUIRTLE, CHARMANDER, or PIKACHU")
confirm("You encountered a wild pokemon!")
var inPokemon = null /*Pokemon{party1}; Here i want party1 to be user input selecting a pokemon, so i can call Pokemon.party1 //which could equal "PIKACHU"//*/
var encounter = Math.floor(Math.random() * 10);
var Pokemon = {
  Charmander: {
    name: "Charmander",
    moves: [moves.EMBER, moves.SCRATCH, moves.GROWL],
    stats: [5, 20, 5, "FIRE"]
  },
  Pikachu: {
    name: "Pikachu",
    moves: [moves.SPARK, moves.SCRATCH, moves.SAND_ATTACK],
    stats: [5, 25, 6, "ELECTRIC"]
  },
  Bulbasaur: {
    name: "Bulbasaur",
    moves: [moves.BULLET_SEED, moves.POUND, moves.SAND_ATTACK],
    stats: [5, 22, 3, "GRASS"]
  },
  Squirtle: {
    name: "Squirtle",
    moves: [moves.BUBBLE, moves.POUND, moves.GROWL],
    stats: [5, 18, 7, "WATER"]
  }
}
var moves = {
  BUBBLE: {
    name: "BUBBLE",
    stats: [12, "WATER"],
    effect: null
  },
  POUND: {
    name: "POUND",
    stats: [10, "NORMAL"],
    effect: null
  },
  GROWL: {
    name: "GROWL",
    stats: [0, "NORMAL", /*here I want it to be something like (Pokemon.party1.stats[2]*(.2) //reduced by 20%// */ ]
  },
}

我的两个问题是相似的,并在上面的代码中提到,我希望一个对象的属性由于外部变量或另一个对象的属性而改变。显然,我不知道该怎么做。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

Object.defineProperty(<your array>, "<the index>", {
    get() {
        return <enter relative value here>;
    }
});

示例:

&#13;
&#13;
let array = [1, 2, 3];
Object.defineProperty(array, "3", {
  get() {
    return array[0] * array[1];
  }
});
console.log(array[3]);//1*2=2
array[0] = 7;
console.log(array[3]);//7*2=14
array[1] = 3;
console.log(array[3]);//7*3=21
&#13;
&#13;
&#13;