how can I refactor this?
As for now, when I prepare my data to be sent by Ajax request to my web app, I just concat my JS arrays (with placing -1
between them as separator - values can be positive only, so -1
means start of new array). This seems a bit ugly for me, so I'm wondering what would be best practice to refator this.
var online1 = [];
var online2 = [];
var online3 = [];
var online4 = [];
for(i = 0 ; i < listOfPlayers.length ; i++) {
var player = listOfPlayers[i].href;
var uid = player.substring(player.lastIndexOf('=') + 1);
if(onlineStatus[i].className ==开发者_开发百科 "online1"){
online1.push(uid);
}
if(onlineStatus[i].className == "online2"){
online2.push(uid);
}
if(onlineStatus[i].className == "online3"){
online3.push(uid);
}
if(onlineStatus[i].className == "online4"){
online4.push(uid);
}
}
online1.push(-1);
online2.push(-1);
online3.push(-1);
online4.push(-1);
var result = online1.concat(online2, online3, online4);
//...
ajaxRequest.send("result="+result);
You could do two things:
Use an object, stringify it using
JSON.stringify
. You can parse it usingJSON.parse
, even server-side solutions exist.JSON
is available in recent browsers and as library.Make the
if
generic.
E.g.:
var online = {1: [],
2: [],
3: [],
4: []};
for(i = 0 ; i < listOfPlayers.length ; i++) {
var player = listOfPlayers[i].href;
var uid = player.substring(player.lastIndexOf('=') + 1);
var number = onlineStatus[i].className.substring(6);
online[number].push(uid);
}
var result = JSON.stringify(online);
//...
ajaxRequest.send("result="+result);
精彩评论