我希望这些消息随机显示,但是不再重复,直到遍历所有消息为止。为什么某些消息被跳过或我返回“未定义”?

var ranNums = [],
    container = $('#container'),
    messages = [
    'message 1',
    'message 2',
    'message 3',
    'message 4'
  ],
  totalMessages = messages.length;

function waitForNext() {
setTimeout(function(){
  changeMsg();
}, 1000);
}

function getNewRanNum() {
var num = Math.floor(Math.random() * totalMessages);

  if(ranNums.indexOf(num) > -1) {
  getNewRanNum();
  return;
} else {
  ranNums.push(num);
  console.log(num, ranNums);
  return num;
}
}

function changeMsg() {
var newMsg = getNewRanNum();

container.append(messages[newMsg] + '<br>');

if (ranNums.length === totalMessages) {
  console.log('end');
  return false;
}

waitForNext();
}

changeMsg();

最佳答案

在某些情况下,您的getNewRanNum函数将return: num,在其他情况下将返回undefined(带有return;语句)。如果您打算递归调用,则需要返回最终递归调用的num。像这样

function getNewRanNum() {
var num = Math.floor(Math.random() * totalMessages);
  if(ranNums.indexOf(num) > -1) {
      return getNewRanNum();
   } else {
      ranNums.push(num);
      console.log(num, ranNums);
      return num;
   }
}

09-26 19:00