有人可以告訴我這段代碼有什麼問題嗎?一:我沒有得到期望的結果,和兩個:我得到着名的「不要在循環內部的功能」。我怎樣才能解決這個問題?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);
}
};
在什麼,'結果[ID] =名'name';'?? –
@SudhansuChoudhary - 看到前一行。它是參數名稱。 – Quentin
那麼,在這種情況下,新功能的創建不會產生意外的行爲,所以你真的不需要改變它。但是,您可以通過在循環外部移動函數聲明來優化代碼,並反覆重複使用相同的函數。 –