简体   繁体   English

当一个函数什么都不返回时,为什么返回值不为空?

[英]when a function return nothing, why the return value is not null?

Why the value of x is undefined in case 1;为什么在案例 1 中 x 的值未定义; Why doesnt it also be null like case 2?为什么它也不像案例 2 那样为空? My understanding is that , in case 1, since f has no return value, so x is pointing to null (no return value)我的理解是,在情况 1 中,由于 f 没有返回值,所以 x 指向 null(没有返回值)

Case 1

f = () => {return}

x = f()

console.log(x) // -->undefined

------------------

f = () => {return null}

x = f()

console.log(x) // -->null

Because the specification says so :因为规范是这样说的

A return statement causes a function to cease execution and, in most cases, returns a value to the caller. return语句会导致函数停止执行,并且在大多数情况下,会向调用者返回一个值。 If Expression is omitted, the return value is undefined .如果省略Expression ,则返回值为undefined Otherwise, the return value is the value of Expression .否则,返回值为Expression的值。

据我所知,当某些东西没有被传递时,函数必然会返回一些东西,默认情况下它是undefined的,就像如果你在没有任何参数的情况下记录它会记录未定义一样。

console.log() // undefined

Basically, when you define a variable without assigning a value, It will become undefine.基本上,当您定义一个变量而不赋值时,它将变为未定义。

When you assign a "Null" value, the value of the variable become null (you are indeed assigning a value)当您分配“空”值时,变量的值变为空(您确实在分配一个值)

In your case, you dont return a value(not assigning any value), you get a undefine在你的情况下,你不返回一个值(不分配任何值),你得到一个 undefine

Hope this makes it clearer for you希望这能让你更清楚在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM