我正在编写一个程序,它从文件中获取一些数据(在这种情况下,是一个 ID 列表)。然后,该程序获取 ID,与天气服务器连接,获取服务器返回的信息,并对其进行解析。
然后它按城市名称的顺序对数据进行排序,并将其推送到一个数组中。我正在尝试将其打印出来,但是当我打印数组时,我不断得到以下输出:
[ { string: 'Dallas, TX : 91' },
{ string: 'Houston, TX : 86' },
{ string: 'Houston, TX : 86' },
{ string: 'Jacksonville, FL : 83' },
{ string: 'Laguna Hills, CA : 67' },
{ string: 'New York, NY : 91' },
{ string: 'Seattle, WA : 62' } ]
当然,我希望包括方括号和逗号。但是,为什么要打印出“字符串:”和花括号?
这是我的来源:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var lineReader = require('line-reader');
var cityList = [];
var numItems = 0;
var needToPrint = 0;
lineReader.eachLine('IDList.txt', function(line, last) {
numItems++;
getResponse(line, textParse);
});
var getResponse = function(id, callback){
var request = new XMLHttpRequest;
request.open("GET", "http://weather.yahooapis.com/forecastrss?w=" + id +"&u=f");
request.onreadystatechange = function(){
if(request.readyState === 4 && request.status === 200){
var type = request.getResponseHeader("Content-Type");
if(type.indexOf("xml") !== -1 && request.responseXML)
callback(request.responseXML);
else if(type === "application/json")
callback(JSON.parse(request.responseText));
else
callback(request.responseText);
}
};
request.send(id);
}
var textParse = function (input)
{
var index = input.indexOf("city=\"") + "city=\"".length;
var endIndex = input.indexOf("\" region=\"");
var city = input.substring(index, endIndex);
index = input.indexOf("region=\"") + "region=\"".length;
var state = input.substring(index, index + 2);
index = input.indexOf("temp=\"") + "temp=\"".length;
endIndex = input.indexOf("\"", index);
var temp = input.substring(index, endIndex);
var obj = new location(city, state, temp);
cityList.push(obj);
cityList.sort(sortFunc);
needToPrint++;
if(numItems === needToPrint)
printData(cityList);
}
var location = function (city, state, currentTemp)
{
this.string = city + ", " + state + " : " + currentTemp;
};
var sortFunc = function(input1, input2)
{
if (input1.string < input2.string) //sort string ascending
return -1
if (input1.string > input2.string)
return 1
return 0 //default return value (no sorting)
}
var printData = function(objectList){
console.log(objectList);
}