2017-04-25 133 views
-1

是否有可能創建for循環創建函數(等)?只是爲了減少硬編碼,因爲我在數組中有很多值。我在這裏我的代碼,它不起作用。是否可以在創建函數時創建for循環?

var obj=["backupF31","backupF32","backupF33","backupF34","backupF35"]; 
 

 
for (var i = 0; i < obj.length; i++) { 
 
    function obj[i]() 
 
    { 
 
    var data = {}; 
 
      $.ajax({type: 'POST', data: JSON.stringify(data), contentType: 'application/json', 
 
\t \t \t \t \t url: '/legone/survey/'+obj[i]+'', \t \t \t \t \t \t 
 
        success: function(data) { 
 
         } 
 
        }); 
 
\t alert("Sucessful backup on "+obj[i]+"); 
 
    } 
 
}

從上面的代碼中,我只是想插入在obj中的數組的值[I]感謝

回答

1

我不知道你在想什麼在這裏實現,但如果你想創建一個後來調用的函數列表,這段代碼可能會幫助你開始:

var obj=["backupF31","backupF32","backupF33","backupF34","backupF35"]; 
 

 
var functions = obj.map(function(key) { 
 
    return function(data) { 
 
    $.ajax({ 
 
     type: 'POST', 
 
     data: JSON.stringify(data), 
 
     contentType: 'application/json', 
 
     url: '/legone/survey/'+key+'', 
 
     success: function(response) { 
 
     data[key] = response 
 
     } 
 
    }); 
 
    alert("Sucessful backup on "+obj[i]+"); 
 
    } 
 
} 
 

 
var data = {}; 
 
functions.forEach(function(f) { 
 
    f(data); 
 
});

如果這不是你想要的,請評論:)

1

這可能是做你想做的事情的一種方式:

function doThing(message) 
{ 
    var data = {}; 
    $.ajax({type: 'POST', data: JSON.stringify(data), contentType: 'application/json', 
       url: '/legone/survey/'+message+'',      
       success: function(data) { 
        } 
       }); 
    alert("Successful backup on "+message+"."); 
} 

var obj=[doThing.bind(null, "backupF31"), doThing.bind(null, "backupF32"), 
     doThing.bind(null, "backupF33"), doThing.bind(null, "backupF34"), 
     doThing.bind(null, "backupF35")]; 

for (var thisObj of obj) { 
    thisObj(); 
} 

bind()創建一個函數調用預定義參數,因此您可以在創建函數指針數組時捕獲不同的參數。