1
JS新人はこちら。最高の総合能力+得点でプレイヤー名にアクセスし、ボタンがクリックされたときに表示させたいと思っていますが、私は近くにいると思いますが、最後のステップは分かりません。innerTextでオブジェクト名にアクセスする
私は 'endScore'を呼び出すことで関数を返すことができますが、得点の高いプレーヤーである 'result'を取得する方法はわかりません。
どうすればいいですか?事前に
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