I am trying to utilize Google's AJAX Language API to translate each value in an array.
for(var n=0; n < mytext.length; n++) {
google.language.translate(mytext[n], originalLanguage, newLanguage, function(result){
if(!result.error){
document.getElementById("caption") += mytext[n]+" has been translated to "+result.translation;
}
})
}
This correctly translates the entire array, but in the success function called by google.language.translate, n is always equal mycaptions.length. This results in mycaptions[n] returning as undefined (e.g., " has been translated to Hola"). This has been bewildering me for days (why is the value of n inside the callback function always as if you are at the end of the loop???), and I am guessing the answer lies in an obvious bit of programming I just don't get.
This has to do with how closures work in JavaScript; when JavaScript creates a closure, any variables that get used are referenced, rather than copied, so when you construct the anonymous function, it stores a reference to
n
rather than copying the value ofn
. Hence, when it actually gets called, it runs with the current value ofn
(which is the value that gets assigned to it at the end of the loop). The workaround is to create a function that takes a parametern
and returns a closure: