开发者

Optimize loop JavaScript

开发者 https://www.devze.com 2022-12-14 22:49 出处:网络
ai up, look at this silly code. I want to pass either a string or an array and return the data. This code does work, but it sucks. What would you recommend as the best way to remove the duplication an

ai up, look at this silly code. I want to pass either a string or an array and return the data. This code does work, but it sucks. What would you recommend as the best way to remove the duplication and optimizing it as much as possible? thanks :)

var getData = function (dataFile) {

  var ajaxResponse = [],
      loop,
      i;

  if(dataFile instanceof Array) {
    loop = dataFi开发者_开发百科le.length;
    for(i = 0; i < loop; i++) {
      $.ajax({
        url: dataFile[i],
        type: "post",
        async: false,
        dataType: "json",
        success: function (data) {
          ajaxResponse[i] = data;
        }
      });
    }
  }
  else {
    $.ajax({
      url: dataFile,
      type: "post",
      async: false,
      dataType: "json",
      success: function (data) {
        ajaxResponse = data;
      }
    });
  }
  return ajaxResponse;
}

thanks people, I'll have to think about this. I could pass all the params as arrays if i wanted but that would cause me problems elsewhere. Basicaly i need to get the return values in the same way they came in, i.e. a single value or an array. The data being asked for is completely different. I could change it, but ill have to investigate which way is going to be better in the long run.


If i'm understanding the code correctly, this should work:

if(!(dataFile instanceof Array))
    dataFile = [dataFile];

i.e., if it's not an array, create an array that contains only that one item. Then always do the loop, although in some cases it will have only one iteration.

I should add that you want to look into your use of the i variable in the for loop. You should change the declaration to for(var i..., rather than just for(i.... Introducing a variable without the var keyword will always make that variable global. This means that that loop is very likely to change the value of i in a completely different for loop, in another function, and you'll have absoutely no idea what's going on.


I like the elegance of David Hedlund's solution, and I think using only arrays will make life easier for you in the long run. But if that doesn't suit your fancy, try something like this (and please change my silly function names):

var getOneDatum = function (dataFile) {
  var ajaxResponse;
  $.ajax({
    url: dataFile,
    type: "post",
    async: false,
    dataType: "json",
    success: function (data) {
      ajaxResponse = data;
    }
  });
  return ajaxResponse;
}

var singleOrArray = function (fn, input) {
  var output;
  if (input instanceof Array) {
    var loop = input.length;
    output = [];
    for (i = 0; i < loop; i++) {
      output[i] = fn(input[i]);
    }
  } else {
    output = fn(input);
  }
  return output;
}

var getData = function (dataFile) {
  return singleOrArray(getOneDatum, dataFile);
}

The benefit here is that this singleOrArray function is very general, so you can reuse it any time you want to handle data that may or may not be an array.


Good point, Patonza :)

var singleOrArray = function (fn, input) {
  var output;
  if (input instanceof Array) {
    var loop = input.length;
    output = [];
    for (i = 0; i < loop; i++) {
      output[i] = fn(input[i]);
    }
  } else {
    output = fn(input);
  }
  return output;
}

var getData = function (dataFile) {
  return singleOrArray(function (dataFile) {
    var ajaxResponse;
    $.ajax({
      url: dataFile,
      type: "post",
      async: false,
      dataType: "json",
      success: function (data) {
        ajaxResponse = data;
      }
    });
    return ajaxResponse;
  }, dataFile);
}


If you have a really large array that you are looping thorough you can use the following loop syntax to make it slightly faster (Be careful though as IMO it makes it much harder read!)

for (var i = dataFile.length; i--;) {
   // Do loop stuff
}

The reason this is slightly faster is the fact that the condition check and decrement are done in one operation as opposed to two.

0

精彩评论

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