1
JS菜鳥在這裏。我想用最高的組合能力+得分來獲得玩家的名字,並在按鈕被點擊時顯示出來,我想我很接近但是不知道最後一步。使用innerText訪問對象名稱
我可以通過調用'endScore'來返回函數,但不知道如何檢索應該是得分最高的'結果'。
我應該怎麼做呢?
var onButtonClick = function() {
console.log('test');
//define player objects, setting ability//
var playerList = [
{name: "player1", highScore: 1, ability: 8},
{name: "player2", highScore: 1, ability: 7},
{name: "player3", highScore: 1, ability: 6},
{name: "player4", highScore: 1, ability: 5},
{name: "player5", highScore: 1, ability: 4},
{name: "player6", highScore: 1, ability: 3},
{name: "player7", highScore: 1, ability: 2},
{name: "player8", highScore: 1, ability: 1}
];
//calculate progress/score for each player at the tournament and adds to their 'ability', updating the objects above//
for (var i = 0; i < playerList.length; i++) {
var progress=Math.random();
progress=11*progress;
progress=Math.floor(progress);
playerList[i].ability=playerList[i].ability+progress;
console.log(playerList[i])
}
//calculate which player had the highest score/progress//
function endScore() {
var score = 0;
var result = [];
for (var i = 0; i < playerList.length; i++) {
if(playerList[i].ability > score) {
result = playerList[i];
score = playerList[i].ability;
}
}
return result;
}
// set "winner" variable equal to the DOM element//
const winner = document.getElementById("winner1")
// Set the winner's innerText equal to the contents of the 'result' variable//
winner.innerText = result.endScore();
}
document.getElementById("tourn1").addEventListener("click", onButtonClick)
<ul>
\t <li>Player 1</li>
\t <li>Player 2</li>
\t <li>Player 3</li>
\t <li>Player 4</li>
\t <li>Player 5</li>
\t <li>Player 6</li>
\t <li>Player 7</li>
\t <li>Player 8</li>
</ul>
<button id="tourn1">Play tournament 1</button>
<p id="winner1">The winner is...</p>
在此先感謝。
啊,謝謝!感覺這是一個範圍問題,現在有道理。 – Matthew