开发者

Batch translating with Google Language API

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开发者_StackOverflow社区 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 of n. Hence, when it actually gets called, it runs with the current value of n (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 parameter n and returns a closure:

function createSuccessFunction(n) {
    return function() {
          // behavior on success
    };
}

// use createSuccessFunction(n) where you need a callback
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜