javascript - 为什么 JavaScript 中的 return 语句不返回任何内容?

标签 javascript arrays return

在您将此问题标记为重复之前,请理解我是 JS 的新手并且总是害怕问 stackoverflow 的问题。

我不明白为什么调用此函数不会返回任何内容,除非我将函数调用包含在 console.log 中。

如果我将函数调用包含在 console.log 中,我会得到预期的输出“此数组中有 3 个元素”,但是如果没有 console.log,我什么也得不到。

var counter = function (arr) {
    return 'There are ' + arr.length + ' elements in this array';
};

counter(["shaun", "sara", "jessica"])

我想知道的是如何在不使用 console.log 的情况下获取此函数的输出,以及为什么不使用 console.log 不输出任何内容。

最佳答案

console.log() is a function used to print information to the console. return on the other hand is a call to pass some value back up to where the call was made.

Via - CodeCademy Forum


return terminates a function and possibly returns a value to the caller of that function (whereas) console.log() will not influence the flow of your code.

Via - Difference between console.log and return in javascript?


检查并运行以下代码片段,以了解两者如何工作的实际示例:

var x = document.getElementById("first");
var y = document.getElementById("last");
var z = document.getElementById("output");

function printName(){
  z.innerText = fullName();
}

function fullName(){
  console.log(x.value + " " + y.value); // this wont push the concatenated name to printName()
  return x.value + " " + y.value; // this will push the concatenated name to printName()
  
  alert("y u do dis?"); // this won't run anymore since the return statement above prevents the function from invoking anything else
}

document.getElementById("btn").addEventListener("click", printName)
<input type="text" id ="first" />
<input type="text" id ="last" />
<button id="btn">Click Me</button>
<br/>
<div id="full">Hello <span id="output"></span>!!</div>


如果上面的return 语句被移除,console.log() 将不会返回任何东西给printName() 除了显示控制台中的串联名称。

关于javascript - 为什么 JavaScript 中的 return 语句不返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54599060/

相关文章:

javascript - 根据其他数组中的索引对对象数组进行排序

arrays - Swift 中的字典数组

javascript - 在 Javascript 中显示来自数据库的图像链接 javascript 数组的 3 个随机图像

javascript - 重新启动 JavaScript 中的方法

javascript - 在 Chrome 中水平滚动时,平铺背景图像的动画背景位置停止

javascript - MapboxGL 挤出线/圆

c - c中的错误函数返回

swift - (Swift) 混淆了函数内 for-in 循环的返回值和循环之后的返回值(函数内))

javascript - 如何正确使用 Angular 工厂?

javascript - 使用google脚本操作数据条件格式和数据验证