在您将此问题标记为重复之前,请理解我是 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/