2015-06-07 69 views
1

一個簡短的運行 - 我使用wad JavaScript library來創建一個隨機音源。我想有音高之間的發電機「滑」,在僞代碼如下:For循環內if語句不會運行,我不知道爲什麼

  1. 確定當前間距(randomNum)
  2. 確定下一間距(randomNext)
  3. 確定下一間距是否更高或更低的
  4. 播放當前的俯仰和保持它的第二個
  5. 播放當前的俯仰和下間距之間的所有球場迅速送「滑動」效應 - 這是一個不正常的部分!
  6. 播放下一個音高並保持一秒(然後將其重新指定爲當前音高)。

我已經得到了一切工作,除了第5步。我試圖使用一個for循環(根據下一個音調是否更高或更低)在if/else語句中使用計數器遍歷每個音高,但根據我記錄的控制檯語句,,for循環永遠不會運行。

如果我從if語句中刪除for循環並從變量中手動設置其起始符間距,它將按預期方式運行。

我在做什麼錯?我的if語句有什麼問題嗎?用我的for循環?

有問題的代碼位的是:

// play the first pitch  
function playFirst() { 
      if(!stopped){ 
       window.randomNum = Math.round(Math.random()*200 + 100); 
       console.log("randomnum is now "+ randomNum); 
      } 
      playRandom(); 
     } 

// play and loop subsequent pitches 
     function playRandom(){ 
      if(!stopped){ 

       var randomNext = Math.round(Math.random()*200 + 100); 
       console.log("randomNext is now " + randomNext); 

       var howManyCents = randomNum - randomNext; 
       console.log(howManyCents + " cents"); 

// ascending note slide condition 
       if (randomNum < randomNext) { 
        console.log("randomnum is less!"); 

        var inbetweenNum = randomNum + 1; 

// for loop - the part with the problem! 
        for (var i = 0; i < howManyCents; i++) { 
         inbetweenNum = randomNum + i; 
         console.log("inbetween number is " + inbetweenNum); 
         inbetween.play({ pitch : inbetweenNum }); 
         console.log("played inbetween up"); 
        } 
// descending note slide condition 
       } else { 
        console.log("randomnum is more!"); 

        var inbetweenNum = randomNum - 1; 

// another problematic for loop 
        for (var i = 0; i > howManyCents; i--) { 
         inbetweenNum = randomNum - i; 
         console.log("inbetween number is " + inbetweenNum); 
         inbetween.play({ pitch : inbetweenNum }); 
         console.log("played inbetween down"); 
        } 
       } 
// actually play the note 
       bell.play({ pitch : randomNext, wait: 0 }); 
       console.log("played randomnext" + randomNext); 

// reassign the new note as the current note 
       randomNum = randomNext; 
       console.log("randomnum is now" + randomNum); 

       setTimeout(playRandom,1500); // and loop it 
      } 
     } 

和我進行了完整的程序here的的jsfiddle。

任何援助將非常感謝!

+0

看起來'randomNum'在您的賦值語句中可能還沒有值:'var howManyCents = randomNum - randomNext;' – sfletche

+0

randomNum在playFirst函數中分配了一個值。 –

回答

1

該塊的條件是randomNum < randomNext,但howManyCentsrandomNum - randomNext,在這種情況下將爲負數。循環條件,然後 - i < howManyCents,i從0開始,將永遠不會成立。

您可以使用i < -howManyCents,或分配給Math.abs(randomNum - randomNext)howManyCents,或i > howManyCentsi--

+0

我認爲* Math.abs(randomNum - randomNext)已經解決了,謝謝。我不知道這種方法! –