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

break 或 continue 循环函数 #58

Open
susouth opened this issue Dec 9, 2019 · 0 comments
Open

break 或 continue 循环函数 #58

susouth opened this issue Dec 9, 2019 · 0 comments
Labels
JavaScript 跟js相关的面试题 No.58

Comments

@susouth
Copy link
Contributor

susouth commented Dec 9, 2019

📚在线阅读:break 或 continue 循环函数 - No.58

停止循环是循环中一个常见的需求。使用for循环我们可以用break提前结束循环。

const a = [0, 1, 2, 3, 4];
for (var i = 0; i < a.length; i++) {
  if (a[i] === 2) {
    break; // stop the loop
  }
  console.log(a[i]);
}
//> 0, 1

另一个常见的需求使我们需要直接取得变量。

一个快速的方式是使用.forEach,但是这样我们就失去了break的能力。这种情况下,最接近的方式是使用return实现continue的功能。

[0, 1, 2, 3, 4].forEach(function(val, i) {
  if (val === 2) {
    // 怎么停止呢?
    return true;
  }
  console.log(val); // your code
});
//> 0, 1, 3, 4

.some是一个原型方法。他用来检测是否某些元素满足所提供的函数。如果任何元素最终返回true,它就会停止运行。更多解释请看MDN

引子上面链接的一个例子:

const isBiggerThan10 = numb => numb > 10;

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

使用.some我们拥有了类似.forEach的功能,而且使用return实现了break的效果。

[0, 1, 2, 3, 4].some(function(val, i) {
  if (val === 2) {
    return true;
  }
  console.log(val); // your code
});
//> 0, 1

你可以返回false使循环continue到下一个元素。当你返回true时,循环将会break,此时a.some(..)将会return true

// Array contains 2
const isTwoPresent = [0, 1, 2, 3, 4].some(function(val, i) {
  if (val === 2) {
    return true; // break
  }
});
console.log(isTwoPresent);
//> true

还有.every函数同样可以实现此功能。但此时我们需要返回与.some相反的布尔值。

示例
JS Bin on jsbin.com<script src="https://static.jsbin.com/js/embed.min.js?3.39.11"></script>

扩展阅读:

@susouth susouth added JavaScript 跟js相关的面试题 No.58 labels Dec 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 跟js相关的面试题 No.58
Projects
None yet
Development

No branches or pull requests

1 participant