我正在尝试学习JavaScript,并正在为练习制作游戏2048的版本。我的导师为我们设置了一个api来保存高分。我创建了一个功能来执行此操作,以及一个列出高分的功能。它们是单独工作的,但当我尝试在同一个按钮下调用它们时,它们不起作用。
获得分数的功能是:
var GetHighScores = function () {
scoreList = [];
fetch("https://highscoreapi.herokuapp.com/scores").then(function (response) {
console.log("Scores received. Status:", response.status);
return response.json();
}).then(function(data){
//find the list
var list = document.querySelector("#highScores");
list.innerHTML="";
data.forEach(function (entry) {
//create a list item
var item = document.createElement("li");
//populate the list item
item.innerHTML = entry.name + ": " + entry.score;
//append te item to the list
list.appendChild(item);
scoreList.push(entry.score);
});
console.log(scoreList);
});
return scoreList;
};
用于获得高分并发布用户分数(如果它在前十名中)的组合功能是:
var submitScore = function () {
GetHighScores();
var leaderBoard = GetHighScores();
var threshold = parseInt(leaderBoard[0]);
console.log(leaderBoard);
if (score >= threshold) {
var initials = prompt("Enter Your Initials:");
fetch("https://highscoreapi.herokuapp.com/scores", {
method: "POST",
headers: new Headers({
"Content-type": "application/json"
}),
body: JSON.stringify({
name: initials,
score: score
})
}).then(function (response) {
console.log("Score submitted. Status: ", response.status);
console.log(score);
console.log(leaderBoard[9]);
});
} //end of if
};
我在这里缺少一些简单的东西吗?