2016-01-23 57 views
1

有人可以告訴我這段代碼有什麼問題嗎?一:我沒有得到期望的結果,和兩個:我得到着名的「不要在循環內部的功能」。我怎樣才能解決這個問題?Javascript不要讓循環中的函數

// 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); 
    } 
}; 
+0

在什麼,'結果[ID] =名'name';'?? –

+0

@SudhansuChoudhary - 看到前一行。它是參數名稱。 – Quentin

+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)); 
    } 
} 
+0

所有名稱被擡頭之前仍然調用回調 – Prinzhorn

+0

啊,我現在看到問題:)我做了一個編輯,請檢查 – Gavriel

+0

現在,因爲每個異步請求共享相同的'id'變量,所以重新有一個競爭條件。基本上,你最終只會得到'results'結果,它只包含一個以最後一個id爲鍵的條目和最後返回的請求的值(它不一定是最後一個id)。 – Prinzhorn