什么时候在JavaScript函数的末尾添加返回值合适? [英] When is it proper to add a return at the end of a JavaScript function?

查看:44
本文介绍了什么时候在JavaScript函数的末尾添加返回值合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一些开发人员将这样的JavaScript函数放在结尾处:

I have seen some developers place a return at the end of their JavaScript functions like this:

$(".items").each(function(){
    mthis = $(this);
    var xposition = some .x() position value;
    if(xposition < 0){
        mthis.remove();
        return;
    }
});

是否需要退货?我知道 return false 会提前退出循环,并且我知道 return x 返回一个值,但是刚刚返回???是什么意思?

Is having a return even necessary? I know that return false cancels out of a loop early and I know that return x, returns a value, but having just return??? What does that mean?

对不起-我忘了在代码的末尾加上}.返回值是if条件的.

Sorry - I forgot to put an end } at the very end of the code. the return is in the if conditional.

新更新-刚刚发现循环的意图是取消进入循环的第n个.item.所以return false是我的简单替代;(无论如何,这都意味着未定义).谢谢大家的帮助!

推荐答案

您的示例特定于 jQuery.each 如何处理循环函数的返回值.从文档中:

Your example is specific for how jQuery.each handles the return values from a loop function. From the docs:

我们可以在特定的迭代中通过使$ .each()循环中断回调函数返回false.返回非假与在for循环中继续执行语句;它将立即跳到下一个迭代.

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

所以就可以了,返回除 false 之外的任何内容都没有区别,它将继续进行下一个迭代.但是, false 会中断循环.

So there you have it, returning anything else than false makes no difference, it will just move on to the next iteration. false, however, breaks the loop.

请注意, return; return undefined; 完全相同.

这篇关于什么时候在JavaScript函数的末尾添加返回值合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆