gpt4 book ai didi

javascript - if 语句内的 for 循环不会运行,我不知道为什么

转载 作者:行者123 更新时间:2023-11-28 00:13:10 24 4
gpt4 key购买 nike

简要介绍 - 我正在使用 wad JavaScript library创建随机音调发生器。我试图让生成器在音高之间“滑动”,如下伪代码所示:

  1. 确定当前音高(randomNum)
  2. 确定下一个音高(randomNext)
  3. 确定下一个音高是更高还是更低
  4. 播放当前音调并保持一秒钟
  5. 快速播放当前音高和下一个音高之间的所有音高,以产生“滑动”效果 - 这是不起作用的部分!
  6. 播放下一个音高并按住一秒钟(然后将其重新指定为当前音高)。

除了第 5 步之外,我已经完成了所有工作。我尝试使用 for 循环(在 if/else 语句中,根据下一个音高是更高还是更低)使用计数器迭代每个音高,但是 < strong>根据我记录的控制台语句,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
}
}

我已经制作了完整程序的 JSFiddle here .

任何帮助将不胜感激!

最佳答案

该 block 的条件是 randomNum < randomNext ,但是howManyCentsrandomNum - randomNext ,在这种情况下将为负数。循环条件,则 – i < howManyCents ,与 i从0开始,永远不会是真的。

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

关于javascript - if 语句内的 for 循环不会运行,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30698636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com