首页 > 解决方案 > 如何在 Vuejs 中使用 for 循环填充数组

问题描述

我有一个 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++;
        }
      }
    }
  }

标签: javascriptvue.jsvuejs2

解决方案


您需要在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循环,这就是为什么您每次都获得相同的随机值并因此在数组中获得相同的对象。


推荐阅读