在下面的switch语句期间,我遇到了(似乎是)随机承诺错误。我创建了一个随机数,并将其与给定的数组项位置相关联。我在switch语句中使用此位置播放特定的声音。在浏览器中进行测试时,有时会出现如下承诺异常:
playSound @ game.js:29
nextSequence @ game.js:18
(anonymous) @ game.js:45
即使我收到此错误,一切都按预期工作。编辑部分:使用调试器进行调试时;上面的内容间歇地出现
//store colors
var buttonColors = [
"green", //0
"red", //1
"yellow", //2
"blue" //3
]
gamePattern = [ /*Added From nextSequence*/ ]
//Generate a random number
function nextSequence() {
randomNumber = Math.floor(Math.random() * 4)
randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$(`#` + randomChosenColor).fadeOut(100).fadeIn(100).delay(200);
playSound(randomChosenColor);
}
function playSound(color) {
switch (color) {
case 'green':
var greenButton = new Audio('sounds/green.mp3');
greenButton.play();
break;
case 'red':
var redButton = new Audio(`sounds/red.mp3`);
redButton.play();
break;
case `yellow`:
var yellowButton = new Audio(`sounds/yellow.mp3`);
yellowButton.play();
break;
case `blue`:
var blueButton = new Audio(`sounds/blue.mp3`);
blueButton.play();
break;
default:
console.log(`Play Sound Error in playSound Function`)
}
}
nextSequence();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>