我在这里工作刮刀但是我正在努力排序数据。
以下是刮刀代码:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
http.createServer(function (req, res) {
request('http://www.xscores.com/soccer', function (error, response,
html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var list_items = "";
var arr = [];
var arr2 = [];
var j = 1;
$('div.match_line.score_row.other_match.e_true').each(function (i, element) {
var a = $(this).attr('data-home-team');
arr.push(a + " Row Number " + j);
j = j + 2;
//list_items += "<li>" + a + "</li>";
//console.log(arr.length);
});
var j = 2;
$('div.match_line.score_row.other_match.o_true').each(function (i, element) {
var b = $(this).attr('data-home-team');
arr.push(b + " Row Number " + j);
j = j + 2;
//list_items += "<li>" + b + "</li>";
//console.log(arr.length);
});
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
list_items += "<li>" + arr[i] + "</li>";
}
var html = "<ul>" + list_items + "</ul>"
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(html);
console.log(arr.length);
}
});
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');
就问题而言,排序这些元素。
现在排序方式
所以基本上我的数组中的项目按照这样排序1,3,5,7,9,2,4,6,8(缩短)
如何对此进行排序,以便按正确顺序输出?
非常感谢任何有关解决方案的建议
弗雷德里克
答案 0 :(得分:1)
检查下面的arr.sort
方法。
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
http.createServer(function(req, res) {
request('http://www.xscores.com/soccer', function(error, response,
html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var list_items = "";
var arr = [];
var arr2 = [];
var j = 1;
$('div.match_line.score_row.other_match.e_true').each(function(i, element) {
var a = $(this).attr('data-home-team');
arr.push({
html: a,
j: j
});
j = j + 2;
//list_items += "<li>" + a + "</li>";
//console.log(arr.length);
});
var j = 2;
$('div.match_line.score_row.other_match.o_true').each(function(i, element) {
var b = $(this).attr('data-home-team');
arr.push({
html: b,
j: j
});
j = j + 2;
//list_items += "<li>" + b + "</li>";
//console.log(arr.length);
});
arr.sort(function(a, b) {
return a.j - b.j
})
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
list_items += "<li>" + arr[i].html + "</li>";
}
var html = "<ul>" + list_items + "</ul>"
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(html);
console.log(arr.length);
}
});
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');