-3
我有要求調用循環內的函數。我設法寫了一個閉包函數。但它不適合我。請幫助解決這個問題。非常感謝您的幫助。Javascript調用循環內的函數
for(var i = 0; i < pointsData.length; i++){
(function(foo){
routeId = pointsData[i]._id;
colorId = pointsData[foo].route_color;
console.log('color start', colorId);
$.post('commands.php',{command: 'get-route-coords',id: pointsData[foo]._id}
,function(data){
MYMAP.setAllRoutes(last, coordinates, pointsData[foo].route_color);
});
}(i));
}
MYMAP.setAllRoutes = function(center,flightPlanCoordinates,colorId) {
console.log('color ids', colorId);
}
什麼不起作用?你的問題需要更多細節。有錯誤嗎? – Andy 2014-10-09 11:38:14
你在你的函數中使用'foo'(明確的名字!)和'i'。你沒有聲明'routeId','colorId'作爲變量,所以它們是全局變量......但無論如何,你忘了在之後使用它們。您的每行比例接近一個錯誤=>您需要睡覺,或瞭解更多關於Javascript的信息;-)。 – GameAlchemist 2014-10-09 11:52:48