有return语句和没有return语句的函数之间有区别吗
Is there a difference between a function with and without a return statement?
假设有两个相同的函数不返回值
function a() {
// do some interesting things
}
function b() {
// do the same interesting things
return;
}
函数b
显然更详细,但它们之间有什么功能区别吗?
没有真正的区别;两者都将返回CCD_ 2。
没有return语句的函数将返回undefined
,带有空return
语句的函数也将返回。
要自己确认这一点,您可以运行以下代码--FIDDLE:
function a() {
}
function b() {
return;
}
var aResult = a();
var bResult = b();
alert(aResult === bResult); //alerts true
Adam是正确的;这两个函数都返回未定义的值,如果您不关心返回值(或者希望值未定义),那么无论哪种方式都是完全可以的。然而,在更复杂的程序中,从函数显式返回通常更好,特别是因为Javascript程序通常具有复杂的回调机制。例如,在这段代码中(只是比您的代码稍微复杂一点),我相信return语句确实有助于澄清代码:
function someAsyncFunction(someVar, callback) {
// do something, and then...
callback(someVar);
// will return undefined
return;
}
function c(){
var someState = null;
if (some condition) {
return someAsyncFunction(some variable, function () {
return "from the callback but not the function";
});
// we've passed the thread of execution to someAsyncFunction
// and explicitly returned from function c. If this line
// contained code, it would not be executed.
} else if (some other condition) {
someState = "some other condition satisfied";
} else {
someState = "no condition satisfied";
}
// Note that if you didn't return explicitly after calling
// someAsyncFunction you would end up calling doSomethingWith(null)
// here. There are obviously ways you could avoid this problem by
// structuring your code differently, but explicit returns really help
// avoid silly mistakes like this which can creep into complex programs.
doSomethingWith(someState);
return;
}
// Note that we don't care about the return value.
c();
通常您会返回一个值。例如,
function b() {
return 'hello';
}
a = b();
console.log(a);
将向您的控制台输出"你好"。
相关文章:
- jquery if语句返回return wong语句
- 函数在return语句之前返回空对象
- 当使用return语句时,循环不会中断
- 如何在不使用return的情况下跳过下一个if语句
- return语句在JavaScript中使用而不中断函数
- 从 JavaScript 调用的小程序方法中的 return 语句
- 为什么我的子函数需要“return”语句以避免出错?父函数没有“返回”,也没有错误
- 具有多个逗号分隔值的 return 语句
- 为什么“return”不完全停止“if”语句中的函数
- 如果语句基于 return if 一个 $.post 命令
- 在 JS 中显式指定 return 语句与根本没有 return 语句有什么区别
- Return语句在ajax调用之前调用
- dojo中的return语句是如何工作的
- 发送ajax请求时出现return语句问题
- 有return语句和没有return语句的函数之间有区别吗
- return语句在完成任务之前返回
- 在return语句中编写代码,在字符串中添加点
- addEventListener函数定义中return false语句的意义
- 当您从函数返回JavaScript语句时会发生什么,例如return console.log(“Hello”)
- Gulp任务中“return”语句和“callback”引用的用途