我有一个复杂的Javascript数组,当写入控制台时,如下所示:
function Standing(flagsmall, teamname, won, drawn, lost, goalsfor, goalsagainst, points) {
this.flagSmall = flagsmall;
this.teamName = teamname;
this.won = won;
this.drawn = drawn;
this.lost = lost;
this.goalsFor = goalsfor;
this.goalsAgainst = goalsagainst;
this.points = points;
}
var arrStandings = new Array();
serviceUrl = "http://cloudapp.net/odata/Standings?$expand=Team,Stage&$filter=Team/Group/GroupName eq 'A'";
var line = "";
$.getJSON(serviceUrl, function (results) {
$.each(results['value'], function (i, item) {
//calculate points
var points = (item.Won * 3) + (item.Drawn * 1);
var standing = new Standing(item.Team.FlagSmall, item.Team.TeamName, item.Won, item.Drawn, item.Lost, item.GoalsFor, item.GoalsAgainst, points);
arrStandings.push(standing);
arrStandings.sort(sortfunction);
});
});
然而,当我尝试迭代它时,我不能,当我检查它的长度时,它返回0:
console.dir(arrStandings.length);
arrStandings.forEach(function (index) {
...
});
如何访问数组中的对象?
答案 0 :(得分:0)
当我启动一个数组时我遇到了类似的问题,但我放了一个字符串键,数组被转换为Object。返回数组/对象的这段代码长度?
Object.keys(myArray).length
您可以使用for语句迭代对象:
for ( index in arrStanding ){
// your code
}
编辑:
// here you have an array
arrStandings.push(standing);
// ...and after this line?
arrStandings.sort(sortfunction);
此致 凯文
答案 1 :(得分:0)
您的代码并不是100%清晰,但看起来您正在尝试在填充数组之前打印数组的长度。
$ .getJSON是一个异步操作,所以在你写入控制台的时候,它还没有被填充。
javascript控制台中显示的表示在创建数组后首次访问时呈现。