【问题标题】:How to fill an array using a for loop in Vuejs [closed]如何在Vuejs中使用for循环填充数组[关闭]
【发布时间】:2020-01-30 14:15:11
【问题描述】:

我有一个 while 循环,我试图在 VueJS 中设置一个数组。希望在数组中有 3 个对象,每个对象都是使用来自 4 个可能选择的 RNG 创建的。现在,当我遍历它们时,它所做的就是在每个数组槽中复制相同的对象:

methods: {
    createMonster() {
      const randomValue = Math.random();
      while (this.i < 3) {
        if (randomValue < 0.35) {
          this.monster.push({
            active: true,
            type: 'Orc',
            hp: 70
          });
          this.i++;
        } else if (randomValue < 0.7) {
          this.monster.push({
            active: true,
            type: 'Gremlin',
            hp: 60
          });
          this.i++;
        } else if (randomValue < 0.9) {
          this.monster.push({
            active: true,
            type: 'Mage',
            hp: 50
          });
          this.i++;
        } else {
          this.monster.push({
            active: true,
            type: 'Knight',
            hp: 80
          });
          this.i++;
        }
      }
    }
  }

【问题讨论】:

  • randomValue的作业下移一行。

标签: javascript vue.js vuejs2


【解决方案1】:

您需要在while 循环内移动随机数生成。这行const randomValue = Math.random(); 应该在while 循环内:

methods: {
  createMonster() {
    while (this.i < 3) {
      let randomValue = Math.random();
      if (randomValue < 0.35) {
        this.monster.push({
          active: true,
          type: 'Orc',
          hp: 70
        });
        this.i++;
      } else if (randomValue < 0.7) {
        this.monster.push({
          active: true,
          type: 'Gremlin',
          hp: 60
        });
        this.i++;
      } else if (randomValue < 0.9) {
        this.monster.push({
          active: true,
          type: 'Mage',
          hp: 50
        });
        this.i++;
      } else {
        this.monster.push({
          active: true,
          type: 'Knight',
          hp: 80
        });
        this.i++;
      }
    }
  }
}

目前,随机数只生成一次并执行while 循环,这就是为什么您每次都获得相同的随机值并因此在数组中获得相同的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多