简体   繁体   English

在Javascript中,为什么要返回; 什么时候什么都不返回?

[英]In Javascript, why do return; when return nothing?

I thought, if return nothing in a function, then the function returns null itself.我想,如果在函数中什么都不返回,那么函数本身返回 null。

but sometimes, I can see like this code,但有时,我可以看到这样的代码,

function test() {
  // do something
  return;
}

var test = function() { 
  // do something
  return;

}

is the return;是回报; is necessary?是必要的? then why?那么为什么?

  • return; does not return null but undefined不返回nullundefined

  • When you see return;当你看到return; in a code, it's to stop the execution of the function before reaching its end.在代码中,它是在到达结束之前停止函数的执行。 For example:例如:

     function test(a) { if (a === 0) return; console.log(a); }

Here if the value of a is 0 , the console will not log.这里如果a值为0 ,则控制台不会记录。 In other words, test will log anything given to it except the number 0.换句话说, test将记录除数字 0 之外的任何内容。

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

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