我有以下代码:
const rp = require('request-promise');
const cheerio = require('cheerio');
const request = require('request')
homeTeam = []; //home team
awayTeam = []; //away team
openOdds = []; //opening odds
currOdds = []; //current odds
awayPerc = []; //away money distribution
homePerc = []; //home money distribution
//sports action API connection
const options = {
url: 'https://api-prod.sprtactn.co/web/v1/scoreboard/mlb?date=20180520',
json: true
}
//sports action money distribution scrape and push to array
request('https://www.actionnetwork.com/mlb/live-odds', function (err, res, html) {
if (!err && res.statusCode == 200) {
var $ = cheerio.load(html);
$('td.text-right.border-left span:first-child').each(function(i, element) {
const awayPercs = $(this).text();
const homePercs = $(this).next().text();
awayPerc.push({awayPercs})
homePerc.push({homePercs})
});
}});
//home team, away team, opening odds, and closing odds API pull
rp(options)
.then((data) => {
const games = data.games
games.forEach((games) => {
games.teams.forEach((teams, i) => {
if (games.home_team_id == games.teams[i].id) {
homeTeam.push({homeTeam: games.teams[i].full_name});
} else if (games.away_team_id == games.teams[i].id) {
awayTeam.push({awayTeam: games.teams[i].full_name});
}
})
games.odds.forEach((odds, i) => {
if (games.odds[i].type == "game" && games.odds[i].book_id == "15") {
currOdds.push({curAway: games.odds[i].ml_away, curHome: games.odds[i].ml_home})
} else if (games.odds[i].type == "game" && games.odds[i].book_id == "30") {
openOdds.push({openAway: games.odds[i].ml_away , openHome: games.odds[i].ml_home})
}
})
})
})
.catch((err) => {
console.log(err);
})
console.log(awayPerc)
每当我尝试在各自的循环之外记录我的任何数组时,它返回一个空数组。如果我声明函数外部的数组不应该能够在任何地方访问它的结果吗?如果我将数组记录在它的相应循环中,它可以正常工作,但在它之外是空的。
答案 0 :(得分:0)
让你的数组公开,它应该可以工作。