我向API发出了一些请求。它来自游戏。首先我要求获得一个身份证,然后使用该身份证我得到一个现场比赛,而我所取出的是每个人正在玩的角色以及玩家的名字。我在Python中做了这个作为我的第一个脚本,但说实话,我对NodeJS中的方法感到困惑。
问题的根源在于我正在做一个嵌套循环。它打印整个数据加上每个人都玩10次的冠军。
这是请求代码的一部分:
// SUMMONER ID TO FETCH DATA
request.get(`https://lan.api.pvp.net/api/lol/lan/v1.4/summoner/by-name/ronalxo?api_key=${riotKey}`, (err, resp, body) => {
let parseBody = JSON.parse(body);
let summonerID = parseBody.ronalxo.id;
// LIVE GAME
request.get(`https://lan.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/LA1/${summonerID}?api_key=${riotKey}`, (err, resp, body) => {
let parseBodyGameInfo = JSON.parse(body);
let idsSeen = [];
let championBeingPlayed = [];
for (let t in parseBodyGameInfo.participants) {
championBeingPlayed.push(parseBodyGameInfo.participants[t].championId);
}
//console.log(championBeingPlayed);
// CHAMPION TO COMPARE ID WITH KEY AND SEE IF IT MATCHES THEN DISPLAY THE CHAMPION NAME
// THIS IS A NESTED REQUEST
request.get(`https://global.api.pvp.net/api/lol/static-data/lan/v1.2/champion?api_key=${riotKey}`, (err, resp, body) => {
let parsechampionIds = JSON.parse(body);
for (let x in parsechampionIds.data) {
if (parsechampionIds.data.hasOwnProperty(x)) { // LOOKS FOR ID OF CHARACTER
let championId = parsechampionIds.data[x].id;
if (championBeingPlayed.indexOf(championId) !== -1 ) { // THE ID FROM ABOVE GETS MATCHED WITH OTHER IDS HERE TO DISPLAY OTHER DATA
for (var i in parseBodyGameInfo.participants) { // CHECKS FOR PARTICIPANTS ON MATCH
if (parseBodyGameInfo.participants[i].teamId === 100) { // CHECKS THE ID OF THE TEAM THAT THE PLAYER BELONGS TO
if (idsSeen.indexOf(parseBodyGameInfo.participants[i].teamId) === -1 ) { // CHECKS IF TEAM ID IS IN ARRAY
console.log(`***** BLUE TEAM *****`); // I PUT THIS HERE SO IT DISPLAYS ONLY ONCE, NOT 10 TIMES
}
console.log(`${parseBodyGameInfo.participants[i].summonerName} playing ${parsechampionIds.data[x].name}`);
}
idsSeen.push(parseBodyGameInfo.participants[i].teamId);
}
}
}
}
});
});
});
输出是这样的:
Anrez playing Thresh
I AM MIZUKAGE playing Thresh
EriickX playing Thresh
xDBanned playing Thresh
yayobuenavibra playing Thresh
Anrez playing Cho'Gath
I AM MIZUKAGE playing Cho'Gath
EriickX playing Cho'Gath
xDBanned playing Cho'Gath
yayobuenavibra playing Cho'Gath
Anrez playing Xin Zhao
I AM MIZUKAGE playing Xin Zhao
EriickX playing Xin Zhao
xDBanned playing Xin Zhao
yayobuenavibra playing Xin Zhao
正如你所看到的,它打印同一个冠军5次,因为有10个,它被打印10次。显然,这不是我希望它拥有的行为。我希望输出如下:
Anrez playing
I AM MIZUKAGE playing Xin zhao
EriickX playing Thresh
xDBanned playing Cho gath
yayobuenavibra playing Tristana
Anrez playing Miss Fortune
哪个是字符的名称,所以,我想知道将 for loop 放在哪里(除了我应该做的好的重构)。
答案 0 :(得分:0)
似乎缺少检查以匹配 championId 的外部 for 循环的 championId 。尝试添加以下if语句:
let tlsum =
match sum tl with
| None -> (* figure this part out *)
| Some n -> (* figure this part out *)
您可以在this plunker中看到演示 - 控制台语句在浏览器控制台中可见。