Javascript不要在循环中使函数

时间:2016-01-23 20:12:08

标签: javascript function loops

有人可以告诉我这段代码有什么问题吗?一:我没有得到理想的结果,两个:我得到了着名的“不要在循环中制作函数”。我该如何解决这个问题?

// Modify this file to make `getNames` work as described
// The tests in index.html will pass when the function is working
//
// Given a list of ids, this function should
//  - use the nameLookup api to find the name for each id
//  - call the callback argument with an object in the format
//    { 1: 'Name1', 2: 'Name2', 3: 'Name3' }
function getNames(ids, callback) {
  var index,
    id,
    results = { };

  for(index = 0; index < ids.length; index++) {
    id = ids[index];

    nameLookup.nameOf(id, function(name) {
      results[id] = name;
    });
  }

  callback(results);
}

namelookup

// Don't modify this file
//
// This is just here to fake API-like responses
// modify get-names.js instead
var nameLookup = {
  names: {},
  list: ['Adam', 'Ali', 'Alex', 'Brian', 'Cam', 'Chris'],

  // "Asynchronously" looks up the name for an id
  // Calls the callback argument with the name
  nameOf: function(id, callback) {
    var self = this;

    setTimeout(function() {
      // This just provides random results
      var index = Math.floor(Math.random() * self.list.length);
      self.names[id] = self.names[id] || self.list[index];
      callback(self.names[id]);
    }, Math.random() * 200);
  }
};

1 个答案:

答案 0 :(得分:0)

所以在循环之前创建函数:

function getFunc(id) {
  return function(name) {
      results[id] = name;
      done ++;
      if (done == ids.length) {
          callback(results);
      }
    }
}

function getNames(ids, callback) {
  var index,
    id,
    results = { };

  var done = 0;
  for(index = 0; index < ids.length; index++) {
    id = ids[index];

    nameLookup.nameOf(id, getFunc(id));
  }
}