Javascript 函数的第一个返回值未定义?

Javascript 函数的第一个返回值未定义?,javascript,arrays,function,console.log,Javascript,Arrays,Function,Console.log,这里有一个函数,它为每个函数调用返回一个数组元素。它通过检查使用的元素被推送到的另一个数组来避免两次返回相同的元素 问题是,当我第一次运行它时,我总是返回“undefined”。如果我进行了多个console.log调用,则在第一个调用之后的调用将返回一个元素 我想这与我的第一个“如果”语句有关,但我不确定。空数组是否返回长度属性0?这就是我“如果”声明中的问题吗 我感谢所有的帮助,提前谢谢 var fortunesList = [ "A", "B", "C", "D", ];

这里有一个函数,它为每个函数调用返回一个数组元素。它通过检查使用的元素被推送到的另一个数组来避免两次返回相同的元素

问题是,当我第一次运行它时,我总是返回“undefined”。如果我进行了多个console.log调用,则在第一个调用之后的调用将返回一个元素

我想这与我的第一个“如果”语句有关,但我不确定。空数组是否返回长度属性0?这就是我“如果”声明中的问题吗

我感谢所有的帮助,提前谢谢

var fortunesList = [
  "A",
  "B",
  "C",
  "D",
];

  var usedFortunes = [];


var getFortune = fortunesList[Math.floor(Math.random()*fortunesList.length)];

function fortuneCookieGenerator(getFortune) {
  if (usedFortunes.length == 0) {
    usedFortunes.push(getFortune);
  }   
  else if (usedFortunes.length > 0) {
    for (i = 0; i < usedFortunes.length; ++i) {
      if (usedFortunes[i] == getFortune) {
        getFortune = fortunesList[Math.floor(Math.random()*fortunesList.length)];
        i = 0;
      }  
    }
    usedFortunes.push(getFortune);
  }
  return getFortune;
}


console.log(fortuneCookieGenerator());
console.log(fortuneCookieGenerator());
console.log(fortuneCookieGenerator());
console.log(fortuneCookieGenerator());
var fortunesList=[
“A”,
“B”,
“C”,
“D”,
];
var UsedFactors=[];
var getFortune=fortunesList[Math.floor(Math.random()*fortunesList.length)];
函数生成器(getFortune){
如果(UsedFactors.length==0){
使用运气。推(获得财富);
}   
else if(usedfactors.length>0){
对于(i=0;i
getFortune
未定义,因为您将其作为
fortuneCookieGenerator
的参数,但您不传递任何内容。第一次调用函数后,
usedfortues.length
大于0,触发else分支,您将为
getFortune
指定一个新值并返回该值


您可能还受益于这些JS调试指南:,并且。

如果条件不为true,则getFortune()将是未定义的,因此我认为您还需要添加else部分来初始化它。

您的函数具有下一个签名

function fortuneCookieGenerator(getFortune)
这意味着您可以向它传递一个参数,
getFortune
。现在,当您想要调用上述函数时,您可以使用next

fortuneCookieGenerator()
这意味着您在调用函数时没有传递参数。因此,在第一次调用时,
getFortune
尚未定义。此外,变量
usedfactors
仍然为空。因此,

usedFortunes.push(getFortune);
如果调用了块,则从第一个
开始。您正在将未定义的变量推送到数组中。完成后,程序将继续执行

return getFortune;
返回未定义的

在第二次调用时,您仍然没有传递参数,但是变量
usedfactors
now不是空的。因此,它将执行
else if
块。好了,你有

getFortune = fortunesList[Math.floor(Math.random()*fortunesList.length)];
它初始化变量。因此,

return getFortune;
保存某些内容时,您将不再接收未定义的
。这就是为什么在第一次调用时,您会得到
未定义的
,但在第二次和以后的调用中不会得到

首先要这样做:

console.log(fortuneCookieGenerator(getFortune));
或者


语法错误
额外的逗号。您在调用中忘记了getFortune:console.log(fortuneCookieGenerator(getFortune));这修复了未定义的问题,但是现在来自fortunesList数组的元素再次重复它们自己,知道为什么吗?Nvm,我通过在if块中设置I=-1修复了这个问题,if块在else-if块中。哦,谢谢你的链接,我来看看。嘿,卡雷尔,这是一个伟大的崩溃。我希望我也能给你最好的答案,但因为我在阅读了第一个答案后理解了代码中的问题,所以默认情况下,我将它授予了第一个答案。再次感谢你!
function fortuneCookieGenarator(getFortune){
.......