Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

年终讲(5)———— 跳出 for...each #310

Open
lucian55 opened this issue Jan 8, 2019 · 1 comment
Open

年终讲(5)———— 跳出 for...each #310

lucian55 opened this issue Jan 8, 2019 · 1 comment

Comments

@lucian55
Copy link
Member

lucian55 commented Jan 8, 2019

前面的

大家都知道,for...each是不能终止循环并跳出的。那么今天就说一下怎么终止循环并跳出😀

方法一:抛出异常

我抛出异常,你总不能还继续执行吧

[1, 2, 3, 4, 5].forEach(function(v) {
    console.log(v); //只输出1,2
    if (v === 2) throw BreakErr;
  });

方法二:空跑循环

什么是空跑循环呢? 就是在外层加一个标识,在特定情况下改变此标识的值,然后通过if语句判断,空跑后续的循环。

var breakFlag = false;

[1, 2, 3, 4, 5].forEach(function(v) {
  if (breakFlag === true) {
    return false;
  }
  if (v === 2) {
    breakFlag = true
  }
  console.log(v) //只输出1,2
})

方法三:神奇改数组大法

这个方法就比较绕了,可以品一品。 大概意思是:在item === 2的时候,改变了原数组引用的值,因为原数组改变了,则forEach进行到第二项就没了,然后用concat后的新数组赋值给了array,所以array的值看上去并没有变

var array = [1, 2, 3, 4, 5];
array.forEach(function(item, index) {
  if (item === 2) {
    array = array.concat(array.splice(index, array.length - index));
  }
  console.log(item); //只输出1,2
});

方法四:最应该使用的every/some

在需要break的时候,使用 every/some 方法。 这个就比较简单,而且是推荐的了

var a = [1, 2, 3, 4, 5]
a.every(function(item, index, arry) {
    console.log(item); //输出:1,2
    if (item === 2) {
        return false
    } else {
        return true
    }
})
var a = [1, 2, 3, 4, 5]
a.some(function(item, index, arry) {
    console.log(item); //输出:1,2
    if (item === 2) {
        return true
    } else {
        return false
    }
})
@qqkillqq
Copy link

qqkillqq commented Sep 6, 2019

修改索引的可以优化啊,安利一波
https://www.bilibili.com/video/av46607656?from=search&seid=17815265769567067811

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants