我是使用JSON和Javascript的新手,但我正在尝试对Reddit提供的JSON文件的各种值进行排序。在控制台中,我确实看到了来自console.log(posts)的数组和JSON值。但是,console.log(posts.length)语句返回0并且屏幕上没有显示任何内容,我怀疑这是由于我如何在数组中存储和/或检索JSON值。
var minVotes = 5;
var subreddit = "askreddit";
var posts = [];
//Retrieve JSON from Reddit using JQuery
$.getJSON("https://www.reddit.com/r/" + subreddit + "/rising.json?limit=50", function foo(result) {
$.each(result.data.children.slice(0, 50), function(i, post) {
if (post.data.ups > minVotes) {
//Push JSON data to array to be sorted later
posts.push(post.data);
}
})
})
//Sort the array
posts.sort(function(a, b) {
return parseInt(a.data.ups - a.data.num_comments) - parseInt(b.data.ups - b.data.num_comments);
});
console.log(posts);
console.log(posts.length); //returns 0 ???
//Display the content, which doesn't work
for (var i = 0; i < posts.length; i++) {
$("#reddit-content").append('<br>' + "Title: " + posts[i].title);
$("#reddit-content").append('<br>' + "Url: " + posts[i].url);
$("#reddit-content").append('<br>' + "Upvotes: " + posts[i].ups);
$("#reddit-content").append('<br>' + "Comments: " + posts[i].num_comments);
$("#reddit-content").append('<hr>');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reddit-content"></div>
&#13;
答案 0 :(得分:2)
这是因为$.getJSON
的异步性质。如果你在响应处理程序内对数组进行排序,它可以正常工作。
您在排序中还有另一个问题,即访问属性值。我不相信您需要parseInt
,因为JSON.parse
会将这些值作为数字返回。
var minVotes = 5;
var subreddit = "askreddit";
//Retrieve JSON from Reddit using JQuery
$.getJSON("https://www.reddit.com/r/" + subreddit + "/rising.json?limit=50", function foo(result) {
var posts = [];
$.each(result.data.children.slice(0, 50), function(i, post) {
if (post.data.ups > minVotes) {
//Push JSON data to array to be sorted later
posts.push(post.data);
}
});
//Sort the array
posts.sort(function(a, b) {
return parseInt(a.ups - a.num_comments) - parseInt(b.ups - b.num_comments);
});
console.log(posts);
console.log(posts.length);
//Display the content, which doesn't work
for (var i = 0; i < posts.length; i++) {
$("#reddit-content").append('<br>' + "Title: " + posts[i].title);
$("#reddit-content").append('<br>' + "Url: " + posts[i].url);
$("#reddit-content").append('<br>' + "Upvotes: " + posts[i].ups);
$("#reddit-content").append('<br>' + "Comments: " + posts[i].num_comments);
$("#reddit-content").append('<hr>');
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reddit-content"></div>
&#13;