什么是“返回”?用JavaScript做吗? [英] What does "return" do in Javascript?
问题描述
我只是自学了如何使用互联网上的教程进行编码。
我目前正在尝试学习Javascript,但我并没有真正理解返回的目的。在课程结束时,我使用返回功能制作了石头,剪刀,剪刀布游戏。游戏看起来像这样:
I just taught myself how to code with tutorials from the internet. I'm currently trying to learn Javascript and I don't really undesrtand the purpose of "return". I made a "rock, paper, scissors" game at the end of my lesson, using the return function. The game looks like this:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
var compare = function(choice1, choice2){
if(choice1 === choice2){
return "The result is a tie!";
}
else if(choice1 === "rock"){
if(choice2 === "scissors"){
return "rock wins";
}
else{
return "paper wins";
}
}
else if(choice1 === "paper"){
if(choice2 === "rock"){
return "paper wins";
}
else{
return "scissors wins";
}
}
else if(choice1 === "scissors"){
if(choice2 === "paper"){
return "scissors wins";
}
else{
return "rock wins";
}
}
};
compare(userChoice, computerChoice);
如果我使用 console.log(,那会有什么区别。 ...)
而不是 return
在这里?
What exactly would be the difference if I used console.log("....")
instead of "return"
here?
推荐答案
根据W3Schools,
According to W3Schools,
return语句停止执行函数并返回
值
The return statement stops the execution of a function and returns a value from that function.
但是
console.log写入浏览器控制台。
console.log writes into the browser console.
换句话说,您看不到的输出。 console.log
除非您打开开发人员工具
In other words, you can't see the output of console.log
unless you open 'Developer Tools'
根据MDN(可靠得多的来源)
According to MDN (a much more reliable source),
在函数中调用
return
语句时,将停止执行该函数的
。如果指定,给定值将返回给函数调用者
。如果省略表达式,则返回$ un $。以下返回语句均破坏
函数的执行:
When a
return
statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. The following return statements all break the function execution:
return;
return true;
return false;
return x;
return x + y / 3;
但是
console.log()将消息输出到Web控制台。
console.log() outputs a message to the Web Console.
例如,
function myFunction() {
return Math.PI;
}
将返回 3.141592653589793
但是改用console.log,不会在网页上显示任何内容(开发人员工具除外)。
But using console.log instead, would not show anything, on a webpage (except in developer tools).
这篇关于什么是“返回”?用JavaScript做吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!