[英]Difference in returning values outside and inside a callback function for a method
I have a method that executes the following function, yet I noticed I can use return
in both ways. 我有一个执行以下功能的方法,但我注意到我可以同时使用
return
。
Once inside the function: 进入函数后:
this.tasks.forEach(function(task) {
return task.completed = true;
});
Once outside the function: 一旦超出功能范围:
return this.tasks.forEach(function(task) {
task.completed = true;
});
Both times I get the correct result, yet I wonder if there is any difference. 两次我都得到正确的结果,但是我想知道是否有任何区别。
As far as the return statement inside the callback function goes, there is no difference, except for the fact that there is an unnecessary return
statement in the first example. 就回调函数内部的return语句而言,没有什么区别,除了第一个示例中存在不必要的
return
语句。 The return value of the forEach
callback function is unused. forEach
回调函数的返回值未使用。
However, the return statement outside the callback function could make a functional difference, as it will return undefined
in the function it is run in. undefined
is the default return value, so you will only notice a difference if there is code after it that is now being skipped. 但是,回调函数外return语句可以使一个功能上的差异,因为它会返回
undefined
它在运行的功能。 undefined
是默认的返回值,那么你只会注意到一个区别,如果有代码,后现在被跳过。 Of course, calling return
inside the callback will not return the parent function, as your second example will. 当然,在第二个示例中,在回调内部调用
return
不会返回父函数。
forEach
: forEach
的MDN页面 :
forEach()
executes thecallback
function once for each array element;forEach()
对每个数组元素执行一次callback
函数; unlikeevery()
andsome()
, it always returns the valueundefined
.与
every()
和some()
,它总是返回undefined
值。
They're very different but not in a way that necessarily makes any difference in this case. 它们有很大的不同,但在这种情况下并不一定会有所不同。 Having
return task.completed = true
inside the function just has it return true every time, which is ignored by Array.prototype.forEach
. 在函数内部具有
return task.completed = true
时,每次都会使它返回true,这将被Array.prototype.forEach
忽略。 The other way, the result of forEach is returned, which is always undefined
(it's a void function). 另一种方法是,返回forEach的结果,该结果始终是
undefined
(这是一个void函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.