代码之家  ›  专栏  ›  技术社区  ›  Alex_89

控制台中的“未定义”输出,使用console.log()[重复]

  •  0
  • Alex_89  · 技术社区  · 1 年前

    我是JavaScript的新手,试着学习如何读取函数,如果有人能看看这段代码,告诉我为什么我在这里得到“未定义”的输出,那就太好了:

    const myArray = [0, 1, 2, 3, 4, 5];
    
    function arryIncludesMain(arr, item) {
      return arr.includes(item);
    }
    
    function arryIncludesAlt(arr, item) {
      if (arr.includes(item)) {
        console.log("true");
      } else {
        console.log("false");
      }
    }
    
    console.log(myArray.includes(8))
    
    console.log("-----------------------------------------------");
    
    console.log("Main function output:");
    console.log(arryIncludesMain(myArray, 3));
    console.log(arryIncludesMain(myArray, 6));
    console.log("-----------------------------------------------");
    
    console.log("Alt function output:");
    console.log(arryIncludesAlt(myArray, 3));
    console.log(arryIncludesAlt(myArray, 6));
    

    下面是控制台输出:

    false
    -----------------------------------------------
    Main function output:
    true
    false
    -----------------------------------------------
    Alt function output:
    true
    undefined
    false
    undefined
    

    Main和Alt方法在控制台中获得“未定义”输出的区别是什么?这个“未定义”指的是什么?

    3 回复  |  直到 1 年前
        1
  •  2
  •   Mamun    1 年前

    功能 return :

    在JavaScript中,当函数没有 回来 语句,或者当它到达函数末尾而不返回值时,它隐式返回 undefined

    arryIncludesAlt() 没有 回来 语句,相反,它使用 console.log 打印字符串( true false )到控制台。

        2
  •  1
  •   darjow    1 年前

    您得到未定义的原因是,您的arrayIncludesAlt函数没有返回任何内容,而是一个记录 结果。所以你不应该打电话 console.log 关于这个方法。

    不要做:

    console.log(arryIncludesAlt(myArray, 3)); // logs undefined
    console.log(arryIncludesAlt(myArray, 6)); // logs undefined
    

    你应该做:

    arryIncludesAlt(myArray, 3) // will do console.log while calling this function
    arryIncludesAlt(myArray, 6) // will do console.log while calling this function
    

    就像你的 arryIncludesAlt 函数,您已经在记录结果。

        3
  •  1
  •   Jegan M    1 年前

    区别在于“return”语句。它使函数产生结果。

    另一种方法是:

    function arryIncludesAlt(arr, item) {
      if (arr.includes(item)) {
        console.log("true");
      } else {
        console.log("false");
      }
      return arr.includes(item);
    }