如何在咖啡脚本中创建while循环

时间:2013-07-20 18:51:03

标签: javascript coffeescript

任何人都可以解释为什么在转换为javascript时,此coffescript的while循环中的增量i ++被置于while循环之外?

if eventtype is 'test'
  i = 0
  while i < platforms.length
    $.ajax
      url: 'myurl/?id=567&platform='+platforms[i]
      .done (response) -> 
        if platforms[i] is 'tv'
          $scope.lolVdatatv = JSON.parse(response)
          alert response
        if platforms[i] is 'phone'
          $scope.lolVdataphone = JSON.parse(response)
          alert response
        if platforms[i] is 'internet'
          $scope.lolVdatainternet = JSON.parse(response)
          alert response
  i++

以下是转换后的JavaScript:

var i;
if (eventtype === 'test') {
  i = 0;
  while (i < platforms.length) {
    $.ajax({
      url: 'myurl/?id=567&platform='+platforms[i]
    }).done(function(response) {
      if (platforms[i] === 'tv') {
        $scope.lolVdatatv = JSON.parse(response);
        alert(response);
      }
      if (platforms[i] === 'phone') {
        $scope.lolVdataphone = JSON.parse(response);
        alert(response);
      }
      if (platforms[i] === 'internet') {
        $scope.lolVdatainternet = JSON.parse(response);
        return alert(response);
      }
    });
  }
  i++;
}

这导致while循环不退出。

1 个答案:

答案 0 :(得分:1)

Coffeescript就像python一样,缩进敏感。您需要将i++语句进一步缩进到while循环中:

i = 0
while i < platforms.length
  //do things
  i++
  //still inside.
//this is outside of the loop