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无法跳出循环?的更多相关文章

  1. JS中forEach和map的区别

    共同点: 1.都是循环遍历数组中的每一项. 2.forEach()和map()里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input. 3.匿名函数中 ...

  2. js中 forEach 和 map 区别

    共同点: 1.都是循环遍历数组中的每一项. 2.forEach()和map()里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input. 3.匿名函数中 ...

  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 ...

  4. 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 ...

  5. 十 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 ...

  6. js中forEach,for in,for of的区别

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. JS中forEach的用法

    forEach是ES5中操作数组的一种方法,主要功能是遍历数组,例如: 1 2 var arr = [1,2,3,4]; arr.forEach(alert); 等价于: 1 2 3 4 var ar ...

  8. js 中 forEach 和 map

    共同点: 1.都是循环遍历数组中的每一项. 2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input. 3.匿名 ...

  9. 关于js中for in和foreach in的区别

    js 中for in 和foreach in的区别 两个的作用都用来遍历对象,但为什么有了for in语句了还要foreach in语句呢,后来看了下foreach in开发的文档,foreach i ...

随机推荐

  1. [ActionScript3.0] 传递任意数量的参数

    function setAgument(a:int,...rest):void{ for(var i:int=0;i<rest.length;i++){ trace(rest[i]); }}se ...

  2. selenium启动firefox、ie、chrome各浏览器方法

    1.启动firefox浏览器 a.如果你的本地firefox是默认路径安装的话,如下方式即可启动浏览器 WebDriver driver = new FirefoxDriver(); driver.g ...

  3. Codeforces 665D Simple Subset [简单数学]

    题意: 给你n个数,让你从中选一个子集要求子集中的任何两个数相加都是质数. 思路: 一开始把自己坑了,各种想,后来发现一个简单的性质,那就是两个数相加的必要条件是这两个数之中必定一个奇数一个偶数,(除 ...

  4. poj 3295 Tautology

    点击打开链接 Tautology Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8127   Accepted: 3115 ...

  5. Linux场景下的辅助命令操作汇总

    ============================================ 1.客户端: SecureCRT 7.1 或者putty 2.FTP 主要是上传文件往Linux,否则我们就的 ...

  6. Visual 中控制台程序如何使用MFC类库

    unresolved external symbol __beginthreadex错误的解决Win32 Consle Application使用MFC的一些类如CString时编译时相信会很经常遇到 ...

  7. Android开发-API指南-Content Provider基础

    Content Provider Basics 英文原文:http://developer.android.com/guide/topics/providers/content-provider-ba ...

  8. js获取服务器控件DropDownList所选中的各项属性

    var ddl = document.getElementById("DropDownList1"); alert(ddl.selectedIndex);//选择索引值 alert ...

  9. 跟我学 NHibernate (三)

    在使用 NHibernate 时,一定要将Mapping 映射文件,也就是 xml 文件的编译方式设置成 嵌入式,这是因为在 NHibernate 启动时,它会主动的到项目的启动目录中寻找 被设置为嵌 ...

  10. NULL值比较,两个列的合并,列值按条件替换。

    show create table 表名 -- 显示创建表的sql语句. 为已有的表增加新列.alter table 表名 add 列名 int NULL -- 此行加了一个int 类型 默认可以nu ...