0

谁能解释为什么当转换为 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循环不退出。

4

1 回答 1

1

Coffeescript 和 python 一样,对缩进敏感。您需要将i++语句进一步缩进以位于while循环内:

i = 0
while i < platforms.length
  //do things
  i++
  //still inside.
//this is outside of the loop
于 2013-07-20T19:03:30.673 回答