$().each,$.each和arr.forEach对比解析

jQuery中each类似于javascript的for循环
但不同于for循环的是在each里面不能使用break结束循环,也不能使用continue来结束本次循环,想要实现类似的功能就只能用return,
break           用return false
continue      用return ture

<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">   
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>  
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />       
<title>$().each,$.each和arr.forEach对比解析</title>
<style type="text/css">
html {}
body {position: relative;padding: 0;margin: 0;}
</style>
</head>
<body>
<button id="m-btn">Change colors</button>
<span></span> 
<div>1</div> 
<div>2</div>
<div>3</div> 
<div>4</div>
<div id="stop">Stop here</div> 
<div>5</div>
<div>6</div>
<script src="https://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script>
<script>
$("#m-btn").click(function () { 
    $("div").each(function (index, domEle) { 
        // domEle == this 

        if (index === 1) {
            return true;  //相当于continue
        }
        $(domEle).css("backgroundColor", "yellow"); 
        if ($(this).is("#stop")) { 
            $("span").text("Stopped at div index #" + index); 
            return false;  //相当于break
        } 
    });
});

var arr = ['a', 'b', 'c', 'd', 'e'];
arr.forEach(function(item, index) {
    if (item === 'b') {
        return true;  //相当于continue
    }
    if (item === 'c') {
        return false;  //相当于continue
    }
    console.log(index + ':' + item);
});

//$.each方法可用于遍历任何对象。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。
$.each( [0, 1, 2, 3, 4, 5, 6], function(i, n){
    if (i === 1) {
        return true;  //相当于continue
    }
    if (i === 4) {
        return false;  //相当于break
    }

    console.log( "Item #" + i + ": " + n );
});
$.each( { name: "John", lang: "JS" }, function(i, n){
    console.log( "Name: " + i + ", Value: " + n );
});
</script>
</body>
</html>


转载于:https://www.cnblogs.com/xutongbao/p/9924843.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值