js中forEach无法跳出循环?
1. forEach()
forEach() 方法从头至尾遍历数组,为每个元素调用指定的函数。如上所述,传递的函数作为forEach()的第一个参数。然后forEach()使用三个参数调用该 函数:数组元素、元素的索引和数组本身。如果只关心数组元素的值,可以编写只有一个参数的函数——额外的参数将忽略:
var data = [1,2,3,4,5];
//要求和的数组
// 计算数组元素的和值
var sum = 0;
// 初始为0
data.forEach(function(value){ sum += value; });
// 将每个值累加到sum上
sum
// => 15
// 每个数组元素的值自加1
data.forEach(function(v,i, a){ a[i] = v + 1; });
data
// => [2,3,4,5,6]
注意,forEach()无法在所有元素都传递给调用的函数之前终止遍历。也就是说,没有像for循环中使用的相应的break语句。如果要提前终止,必须把forEach()方法放在一个try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止:
function foreach(a,f,t){
try { a.forEach(f,t); }
catch(e){
if(e === foreach.break)return;
else throw e;
}
}
foreach.break = new Error("StopIteration");
转自: 《JavaScript权威指南(6版)》7.9.1 forEach()
2.现在让我们来实践一下吧!!!是不是很兴奋?!是不是很激动?!!是不是迫不及待!!!
Let's Go !!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript"> function skipOutForeach(){ //1.测试 return,return false是否能跳出循环
var arr = [];
arr = getArr(1,30);
console.log(arr);
arr.forEach(function(el,index){
if (el==20) {
console.log("遇到20,能退出吗?");//并不能
return;//return false;
}else{
console.log(el);
}
}); //2.使用异常的方式来跳出forEach循环---------------------------
console.log("-------------------------------")
var myerror = null;
try{
arr.forEach(function(el,index){
if (el==20) {
console.log("try中遇到20,能退出吗?");//
foreach.break=new Error("StopIteration");
}else{
console.log(el);
}
});
}catch(e){
console.log(e.message);
if(e.message==="foreach is not defined") {
console.log("跳出来了?");//
return;
}else throw e;
}//可以跳出来,那么 我们可以重写foreach方法
//-----------------------------
console.log("aaa"); } // skipOutForeach(); //自定义foreach方法(往Array或String的prototype添加也可以)
function fore7(arr,func){
console.log(arr);
for (var i = 0; i < arr.length; i++) {
var ret= func.call(this,arr[i],i);//回调函数
if(typeof ret !== "undefined"&&(ret==null||ret==false)) break;
} } //自定义foreach,的用法
fore7(getArr(1,30),function(a,i){
console.log(i+':'+a);
if (i==20) return false;//跳出循环
}) //返回min,max之间的数组成的数组,无序
function getArr(min,max){
if(typeof min!=='number'||typeof max !== 'number') return [];
var arr = [];
for (var i = min; i <= max; i++) {
if (arr.length<1) {
arr.push(i);
}else{
var len = arr.length;
var rIndex = Math.round(Math.random()*(len-1));
var temp = arr[rIndex];
arr[rIndex] = i;
arr.push(temp);
}
}
return arr;
}
</script>
</body>
</html>
3.for循环
return,break都可以跳出
但是多重循环呢?
aaa://需要将循环命名
for(var i=0;i<10;i++){
for(var j=0;j<5;j++){
if(i==3 && j==4){
break aaa;//跳出循环aaa
}
}
}
alert(i);输出3
4.附录:

StackOverFlow: http://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach
js中forEach无法跳出循环?的更多相关文章
- JS中forEach和map的区别
共同点: 1.都是循环遍历数组中的每一项. 2.forEach()和map()里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input. 3.匿名函数中 ...
- js中 forEach 和 map 区别
共同点: 1.都是循环遍历数组中的每一项. 2.forEach()和map()里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input. 3.匿名函数中 ...
- js中forEach,for in,for of循环的用法详解
一.一般的遍历数组的方法: var array = [1,2,3,4,5,6,7]; for (var i = 0; i < array.length; i) { console.log(i,a ...
- js中forEach,for in,for of循环的用法
from:https://www.cnblogs.com/amujoe/p/8875053.html 一.一般的遍历数组的方法: var array = [1,2,3,4,5,6,7]; for (v ...
- 十 js中forEach,for in,for of循环的用法
一.一般的遍历数组的方法: var array = [1,2,3,4,5,6,7]; for (var i = 0; i < array.length; i++) { console.log(i ...
- js中forEach,for in,for of的区别
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- JS中forEach的用法
forEach是ES5中操作数组的一种方法,主要功能是遍历数组,例如: 1 2 var arr = [1,2,3,4]; arr.forEach(alert); 等价于: 1 2 3 4 var ar ...
- js 中 forEach 和 map
共同点: 1.都是循环遍历数组中的每一项. 2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input. 3.匿名 ...
- 关于js中for in和foreach in的区别
js 中for in 和foreach in的区别 两个的作用都用来遍历对象,但为什么有了for in语句了还要foreach in语句呢,后来看了下foreach in开发的文档,foreach i ...
随机推荐
- ubuntu 14.04 安装git server
版本信息 ubuntu : 14.04.1 git version 1.9.1 perl v5.10.1 ssh OpenSSH_6.6.1p1 本次安装的git server使用gitolite实现 ...
- Python中为什么推荐使用isinstance来进行类型判断?而不是type
转自:http://www.xinxingzhao.com/blog/2016/05/23/python-type-vs-isinstance.html Python在定义变量的时候不用指明具体的的类 ...
- JavaScript显示分页按钮
/** * 获取分页按钮 * @param total_page 总页数 * @param current_page 当前页 * @param num 每页显示多少个分页按钮 * @returns { ...
- Android Screen Monitor抓取真机屏幕
今天看到一款有点意思的开源软件“android-screen-monitor”, 简要记录如下: 1 简介 一款同步手机真机屏幕到PC上的软件(屏幕实时抓取,有点小卡) 2 开源地址 http://c ...
- fatal: Not a git repository (or any of the parent directories): .git
$ git remote add origin https://github.com/heyuanchao/YouxibiClient.gitfatal: Not a git repository ( ...
- 一道 JavaScript 面试题
有一道 JavaScript 面试题. f = function () { return true; }; g = function () { return false; }; (function() ...
- gcc编译, gdb调试, makefile写法
//test.c: #include <stdio.h> int main(void) { printf("hello world!"); return 0; } == ...
- "开发路上踩过的坑要一个个填起来————持续更新······(7月30日)"
欢迎转载,请注明出处! https://gii16.github.io/learnmore/2016/07/29/problem.html 踩过的坑及解决方案记录在此篇博文中! 个人理解,如有偏颇,欢 ...
- JavaScript_1
一.方法 ---------------------Array 对象------------------------ 1.concat() : 将作为参数传递的元素拼接到一个已存在的数组2.pop() ...
- EF调用存储过程遇到的问题
注意 实体类Statistics的字段名和存储过程返回集合的列名要相同才行