2
   var j = 0;
   var batchSize = 100;
   var json_left_to_process = json.length;
   while (json_left_to_process != 0) {
       var url_param = "";
       for (var i = j; i < j+batchSize; i++) {
           url_param += json[i].username + ",";
           json_left_to_process--;
       }
       j += batchSize;
       if (json_left_to_process < 100) {
           batchSize = json_left_to_process;
       }
       url_param.substring(0, url_param.lastIndexOf(','));

      //make ajax request
           $.ajax({
                type: "POST",
                url: "/api/1.0/getFollowers.php",
                data: {param: url_param}
           )};
  }

我不想用

url_param += json[i].username + ",";

相反,我想说

newArray.push(json[i].username) 

接着

url_param = newArray.join(',');

但我也想一次处理数组中最多100 个元素。我该怎么做?

编辑:对不起,我的意思是最多 100 个元素,然后最多 100 个元素,然后最多 100 个元素,等等,直到您处理完所有内容。

4

2 回答 2

3

If you mean you want to join 100 and then another 100 after then you can do it like this.

 newArray.slice(0, 100).join(',');

And then after that

 newArray.slice(100, 200).join(',');

You could create a function like this to automate it.

var array = [1...1000], // The array
    start = 0,          // The index to start at
    step  = 100;        // How many to get at a time

var getBatch = function() {
    var result = array.slice(start, start + step).join(',');
    start += step;  // Increment start
    return result;
};

getBatch(); // === 1, 2, 3, 4, ... 100
getBatch(); // === 100, 101, 102, ... 200

Documentation: https://developer.mozilla.org

于 2013-08-30T20:22:34.383 回答
1

我会使用模数。

var i, start = 0;
var newArray = [];
for (i = 0; i <= json.length; i++) {

   // push whatever you want to newArray

   // if i is dividable by 100 slice that part out and join it
   if (i % 100 === 0) {
      console.log(newArray.slice(start, i).join(','));
      start = i;
   }
}
于 2013-08-30T20:31:44.023 回答