在JS中绘制门票获奖者

时间:2018-03-25 00:58:59

标签: javascript

我试图吸引彩票游戏的获胜者,我完全不确定如何决定用户应该根据彩票号码获胜。

购买门票的用户会被放在购买门票的用户身后。

var lotteryTickets = [
    {
    name: 'John Smith',
    tickets: 291
  },
  {
    name: 'Bob the Builder',
    tickets: 302
  },
  {
    name: 'Elizabeth',
    tickets: 72
  }
]

var lotteryTotal = 0;
lotteryTickets.forEach(function(data){
    lotteryTotal = lotteryTotal + data.tickets;
})

$('.tickets').text(lotteryTotal);

var winningTicket = parseInt(Math.random() * lotteryTotal);
$('.winner').text(winningTicket);

我怎样才能正确决定哪个玩家会赢得彩票? JSFiddle

2 个答案:

答案 0 :(得分:0)

尝试循环访问用户:

var ticket = 0;
var winner = 0;
for (var i = 0; i < lotteryTickets.length; i++) {
    ticket += lotteryTickets[i].tickets;
  if (winningTicket < ticket) {
    winner = i;
    break;
  }
}

$('.user').text(lotteryTickets[winner].name);

您可以将此合并到您必须计算门票总数的第一个循环。

JSFiddle

答案 1 :(得分:0)

蛮力的方式是再次遍历lotteryTickets数组。

function getWinner(lotteryTickets,winningTicket){
var count = 0
lotteryTickets.forEach(function(data){
    count += data.tickets
    if(count >= winningTicket){ 
         return data.name
    }
   }