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

First return value of function undefined?

本文关键字:未定义 返回值 第一个 函数      更新时间:2023-09-26

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

问题是当我第一次运行它时,我总是得到"未定义"。如果我进行多个控制台.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());

getFortune是未定义的,因为您将其作为fortuneCookieGenerator的参数,但您没有传递任何内容。第一次调用函数后,usedFortunes.length大于 0 触发 else 分支,您将一个新值分配给getFortune并返回该值。

您还可以从这些JS调试指南中受益:Creativebloq,MDN,Google和MSDN。

你的函数有下一个签名

function fortuneCookieGenerator(getFortune)

这意味着你可以传递一个参数,getFortune它。现在,当你想调用上面的函数时,你使用下一个;

fortuneCookieGenerator()

这意味着您在不传递参数的情况下调用函数。因此,在第一次调用时,尚未定义getFortune。此外,变量 usedFortunes 仍然为空。因此,

usedFortunes.push(getFortune);

从第一个if块被调用。您正在将一个未定义的变量推送到数组中。一旦完成,程序将继续

return getFortune;

返回undefined .

在第二次调用时,您仍然没有传递参数,但变量usedFortunes现在不为空。因此,它将执行else if块。在那里,你有

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

初始化变量。因此,

return getFortune;

拿着东西,你不再收到undefined了。这就是为什么您在第一次通话时会得到undefined,但在第二次和进一步的电话中却没有。

如果条件不为真,getFortune() 将是未定义的,所以我认为你还需要添加 else 部分来初始化它。

首先这样做:

console.log(fortuneCookieGenerator(getFortune));

function fortuneCookieGenarator(getFortune){
.......