$().each,$.each和arr.forEach对比解析
程序员文章站
2022-05-03 20:11:07
...
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>
推荐阅读