前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Jquery的each(function(){})里:return false相当于break; return ture相当于continue

Jquery的each(function(){})里:return false相当于break; return ture相当于continue

作者头像
celineWong7
发布2023-10-16 17:27:15
1360
发布2023-10-16 17:27:15
举报
文章被收录于专栏:web前端踩坑web前端踩坑

突然有点想不起Jq的each()回调函数里,return truereturn false的行为表现了。所以写下demo记录下。

1. 结论

each(function(){})中: return true(return) 相当于continue,跳出当次循环; return false 相当于 break,跳出当前循环。

2. 案例验证

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">

    var testData = [
        {
            "id":1,
            "name":"aa",
            "age": 8

        },
        {
            "id":2,
            "name":"bb",
            "age": 12

        },
        {
            "id":3,
            "name":"cc",
            "age": 18

        },
        {
            "id":5,
            "name":"ee",
            "age": 1

        },
        {
            "id":4,
            "name":"dd",
            "age": 22

        },

    ]

    $(testData).each(function(){
        if (this.age >= 18) return true;
        console.log(this); // 返回 年龄 8/12/1
    });

    $(testData).each(function(){
        if (this.age >= 18) return false;
        console.log(this);// 返回 年龄 8/12
    });
    </script>

</body>
</html>

由于参考文章都提及需要通过try-catch来跳出函数,于是我又尝试each遍历标签jq对象,结果发现上面的结论是ok的。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div>8</div>
    <div>12</div>
    <div>18</div>
    <div>1</div>
    <div>22</div>

    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">

    $('div').each(function(){
        if (Number($(this).text()) >= 18) return true;
        console.log('test-for-return-true: ',$(this).text()); // 返回  8/12/1
    });

    $('div').each(function(){
        if (Number($(this).text()) >= 18) return false;
        console.log('test-for-return-false: ',$(this).text());// 返回  8/12
    });
    </script>

</body>
</html>

参考文章:

  1. jquery中each函数的return
  2. Jquery的each里面用return false代替break; return ture 代替continue 两篇文章都提到了:、 return true(return) 相当于continue,跳出当次循环; return false 相当于 break,跳出当前循环。 但又都提到需要用try-catch来跳出函数。有点奇怪,个人测试return false;在满足条件的时候就会跳出each循环。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 结论
  • 2. 案例验证
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档