【问题标题】:Why function is executed first in console.log?为什么函数首先在console.log 中执行?
【发布时间】:2019-10-03 11:08:38
【问题描述】:

看看这个sn-p:

let first = 1;

function second() {
  console.log(2);
}

console.log(first, second()); // 2 1

我希望它按顺序打印1 2 而不是2 1。为什么函数second首先执行? 我观察console.log 的两个参数是否都是函数,它们的传递顺序被保留(见下面的例子)

function first() {
  console.log(1);
}

function second() {
  console.log(2);
}

console.log(first(), second()); // 1 2

请用相关资源解释这种行为。

【问题讨论】:

  • 由于second 后跟(),因此您将其称为内联,其输出将作为输入传递给console.log
  • “请用相关资源解释这种行为”:这听起来像是家庭作业指导。

标签: javascript console console.log


【解决方案1】:

参数列表中的所有参数在调用包含参数列表的函数之前进行评估。所以

someFn(first(), second());

总是调用first,然后调用second(连同任何其他参数),直到它出现像

这样的中间值
someFn(firstResultExpression, secondResultExpression);

此时someFn 将使用那些(现已解决的)表达式调用。

在这种情况下,someFn 恰好是 console.log。因此,如果 first()second() 自己记录任何内容,这些日志将始终首先出现,然后最后一个 someFn 开始执行任何操作。

【讨论】:

    【解决方案2】:

    帖子有点误导,因为评论表明输出是2 1

    console.log(first, second()); // 2 1
    

    但实际输出的是:

    2
    1 undefined
    

    我们首先得到2 输出,因为console.log(first, second()) 调用second() 并在console.log 中输出2

    请注意,函数 second() 不返回任何内容。 如果函数省略返回值,则返回 undefined

    然后评估console.log(first, undefined),我们得到输出

    1 undefined
    

    请注意,如果 second() 返回一个值(例如 3):

    let first = 1;
    function second() {
       console.log(2);
       return 3;
    } 
    console.log(first, second());
    

    那么输出就是

    2
    1 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多