为什么无论是否 return `console.log()` 都会得到完全相同的结果?

Why do you get the exact same result whether you return `console.log()` or not?

为什么调用console.log()

function test1() {
  console.log('test1')
}

// or ES6
const test2 = () => { console.log('test2') }

给出与 returning console.log()

相同的结果
function test3() {
  return console.log('test3')
}

// or ES6
const test4 = () => console.log('test4')

test1() // -> test1 undefined
test2() // -> test2 undefined
test3() // -> test3 undefined
test4() // -> test4 undefined

虽然我理解没有 显式 return 的函数将始终 return undefined,但对我来说这似乎违反直觉 returning console.log() 的结果给出完全相同的输出。

我想你应该通过看这个得到更好的理解:

const realConsoleLog = console.log
console.log = (...val) => {
  realConsoleLog(...val)
  return val
}
const noReturn = () => { console.log('yep') }
const doesReturn = () => console.log('yep')
const a = noReturn()
const b = doesReturn()
console.log(`a is ${a}`)
console.log(`b is ${b}`)

如果您 运行 程序,您会注意到 noReturn()doesReturn() 函数在您将它们分配给变量时执行。所以在第一种情况下,函数正在执行它的块,然后 return 什么都没有,因此 a 是 undefined。但是在 doesReturn 函数中,您实际上是在执行 console.log 方法,我们已经将其调整为 return 所有原始参数,然后 returning 变量console.log return秒。由于原来的 console.log 没有 return 任何东西,所以你得到 undefined 作为答案。

Javascript 没有 void return 类型规范,因此如果没有这样的显式 return 任何执行上下文停止,undefined 将得到 returned.

证明 - JavaScript 中的 void 是一个计算其旁边表达式的运算符。无论计算哪个表达式,void always returns undefined

你可以得到这样的想法,每当你在浏览器中使用 console,即使你给变量赋值,你也会看到 undefined 得到 returned来自 main 线程执行上下文 return

找到了这个有很好解释的答案 -