lundi 6 décembre 2021

How to get a random element from an array of objects using probabilities in vuejs

I try to call multiple times a method that draw an element from an array using probabilities.

My first method (first_function) is a promise that when resolved return this array :

[
          [
            {
              cardName: 'Energy Fire', cardRatio: 50
            },
            {
              cardName: 'Energy Water', cardRatio: 50
            }
          ],
          [
            {
              cardName: 'Charizard', cardRatio: 10
            },
            {
              cardName: 'Pikachu', cardRatio: 30
            },
            {
              cardName: 'Rayquaza', cardRatio: 60
            },
          ]
 ]

When the promise is resolved, i call another method (second_function) :

      my_promise.then(result => {
        for (const position in result ) {
          this.second_function(result[position])
        }    
      })

There is my second method (second_function) :

    second_function(pull) {
          var winner = Math.random() * 100;
          var threshold = 0;
          for (let i = 0; i < pull.length; i++) {
              threshold += pull[i].cardRatio;
              if (threshold > winner) {
                return console.log('winner',pull[i])
              }
          }
    }

I want to draw a random card from each array (this is why i call multiple times second_function in the first_function) but the problem is just one draw is resolved (i see just one console.log). However, second_function is called multiple times like expected but it looks like the for loop in the second_function is called one time only.




Aucun commentaire:

Enregistrer un commentaire