英文:
How does a function containing console.log() in it behave, when its return value is passed to a console.log as a parameter?
问题
我已经创建了一个函数,它通过console.log()显示一个参数值,并返回一个值。所以我尝试了一下,调用了另一个console.log,在其中我放了两个参数,第一个是一个字符串,第二个参数是我创建的这个函数,其中有一个console.log()。输出让我感到困惑。
我期望的输出是'hello',然后是5,然后是'hi',但实际输出是5,然后是'hello'和'hi'。请帮助,因为这样的输出毫无道理。谢谢。
英文:
I have created a function that displays a parameter value via console.log() within it, and returns a value as well. So I played a bit, and called another console.log, where I've put two parameters, first being a string, and a second parameter being this function that I've created that has a console.log() in it. The output confuses me.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let fun = function (m = 5) {
console.log(m);
return 'hi';
};
console.log('hello', fun());
<!-- end snippet -->
I expected the output to be 'hello' followed by 5 and then 'hi', but the actual output is 5 followed by 'hello' and 'hi'. Please help, as this doesn't make sense as it is. Thanks.
答案1
得分: 2
Sure, here is the translation:
fun()
必须在其返回值可以传递回调用函数之前 完全 被评估。
由于 fun()
包含 console.log(m)
,因此首先记录 m
。
英文:
fun()
has to be fully evaluated before its return value can be passed back to the calling function.
Since fun()
includes console.log(m)
, m
is logged first.
答案2
得分: 1
当执行 console.log('hello', fun());
时,需要先评估两个参数,然后才能调用 console.log
。
fun()
的评估会执行函数内部的代码。这里首先调用 console.log(m)
,因此这个输出是第一个。然后将返回值('hi')用作传递给 console.log
的第二个参数。只有在这之后第二个日志才会实际打印出来。
英文:
When console.log('hello', fun());
is executed, both arguments need to be evaluated before console.log
can be called.
The evaluation of fun()
executes the code inside the function. console.log(m)
is called here, so this output is first. The return value ('hi'
) is then used as the second argument to console.log
. Only after this is the second log actually printed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论