I'm trying to get the variable with the winner. I ask for the highest number but how get I get the according player / variable name:
var A = 0;
var B = 0;
var C = 0;
var D = 0;
var E = 0;
var F = 0;
var G = 0;
var H = 0;
$('.answer').on('click', function (evt) {
const types = $(this).data("typ").split(" "); // split on space.
const active = $(this).is('.active');
types.forEach(typ => {
if (active) {
window[typ]--
} else {
window[typ]++
}
})
console.log(A,B,C,D,E,F,G,H)
$(this).toggleClass("active");
});
$('.fin').on('click', function (evt) {
var players = ['playerA': A, 'playerB': B,'playerC': C,'playerD': D,'playerE': E,'playerF': F,'playerG': G, 'playerH': H];
var winner = Math.max.apply(null, players );
alert(winner, 'wins');
});
Thanks in advance!
You should use an object to store your values with play names (i.e. {} rather than an array which uses []).
You can then use the answer from here to get the highest value.
Working Demo:
var A = 0;
var B = 1;
var C = 2;
var D = 3;
var E = 9;
var F = 5;
var G = 6;
var H = 7;
$('.fin').on('click', function (evt) {
var players = {'playerA': A, 'playerB': B,'playerC': C,'playerD': D,'playerE': E,'playerF': F,'playerG': G, 'playerH': H};
var winner = Object.keys(players).reduce(function(a, b){ return players[a] > players[b] ? a : b });
alert(winner, 'wins');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="fin">Fin</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With