Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
How to add weight of item for randomizing

I am learning to code Javascript and I am currently trying this out! I have an object of 'player' and with chestRewards. In the chest, there are some items to be randomly given. How can I add weight to different items in the array so that item 'gold' is not so frequently given out(rare item). I am also confused with the output, it is printing undefined but I don't understand where that is coming from.

const lootBoxA = ['gold', 'silver', 'shirt', 'shorts'];

const player = {

  chestReward: lootBoxA,

    currentReward(){

      while (this.currentReward){
        this.currentReward = this.chestReward[Math.floor(Math.random() * 4)];
        console.log(this.currentReward);

      if (this.currentReward === 'gold'){
        console.log('Bonus!');
      }break;
    }
  }
}
console.log(player.currentReward()); 
/*Outputs 
gold
Bonus!
undefined*/
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You will need more information than just the name of your items. So, instead of representing your items with string, you can use objects :

const lootBoxA = [
  { name: 'gold', probability: 0.1 },
  { name: 'silver', probability: 0.3 },
  { name: 'shirt', probability: 0.7 },
  { name: 'shorts', probability: 0.5 }
];

That way, you give each item a probability to get picked.

Then, I see no reason why the current reward of your player should be a function (currentReward()). It can just be a property, so you would have something like that :

const player = {
  name: 'Henry',        // for example
  currentReward: null   // the player starts without reward
}

You can have a function to pick a reward for your player. It will take a "lootBox" and pick an item with the right probability :

function pickItemFromLootBox(lootBox) {
  const randomIndex  = Math.floor(Math.random() * lootBox.length);
  const randomNumber = Math.random(); // between 0 and 1
  
  const selectedLootBoxItem = lootBox[randomIndex];

  if (selectedLootBoxItem.probability >= randomNumber) {
    return selectedLootBoxItem;
  } else {
    return null; // no item selected
    // or if you want to always select an item, replace the above line with this : 
    // return pickItemFromLootBox(lootBox);
  }
}

Now that you have a player, a lootBox and a function to pick an item from the lootBox, you can do what you want :

player.currentReward = pickItemFromLootBox(lootBoxA);

if (player.currentReward !== null && player.currentReward.name === 'gold') {
  console.log('Bonus !')
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda