为什么使用return代替console.log? [英] Why is return used instead of console.log?

查看:484
本文介绍了为什么使用return代替console.log?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Codecademy学习JS。我正在此练习

I'm trying to learn JS from Codecademy. I'm doing this excercise.

有人可以告诉我为什么使用 return 而不是 console.log吗? ()
我不完全了解返回的工作方式。

Can someone please tell me why return is used instead of console.log()? I don't fully understand how return works.

推荐答案

返回具有与其他语言几乎相同的行为。

return has pretty much the same behavior as it does in other languages.

来自返回MDN


在函数中调用return语句时,该函数的执行将停止。如果指定,给定值将返回给函数调用者。如果省略该表达式,则返回undefined。

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.

这基本上是指在调用函数 foo()具有类似 return 1的语句; 它将具有 1 这样: var bar = foo(); // bar = 1

What this basically means is that when you call a function foo() that has a statement like return 1; it will have the value of 1 so: var bar = foo(); // bar = 1

function foo() {
    return 1;
}
var bar = foo(); // bar = 1

console.log()如果您正在控制台中运行该程序,可能会造成混淆,它会将值打印到控制台,因此如果我们之前的函数 foo 函数foo(){console.log(1); } 我们的 var bar = foo(); 实际上会将 bar 设置为未定义

console.log() can be confusing if you're running the program in the console, it prints the value to the console so if our function foo from before was function foo() { console.log(1); } our var bar = foo(); would actually set bar to undefined.

function foo() {
    console.log(1);
}
var bar = foo(); // bar = undefined

console.log()MDN

这篇关于为什么使用return代替console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆