开发者

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:

  1. Use an object, stringify it using JSON.stringify. You can parse it using JSON.parse, even server-side solutions exist. JSON is available in recent browsers and as library.

  2. 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜