“返回"是什么意思?用Javascript做?
我刚刚通过互联网上的教程自学了如何编写代码.我目前正在尝试学习 Javascript,但我并没有真正理解返回"的目的.在课程结束时,我使用 return 函数做了一个石头剪刀布"游戏.游戏是这样的:
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
的输出,除非你打开'Developer Tools'
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
语句时,执行此功能已停止.如果指定,则返回给定值函数调用者.如果省略表达式,则 undefined 为而是返回.以下 return 语句都打破了函数执行:
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).
相关文章