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*/