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

关于return和break、continue #32

Open
lovelmh13 opened this issue May 4, 2020 · 0 comments
Open

关于return和break、continue #32

lovelmh13 opened this issue May 4, 2020 · 0 comments

Comments

@lovelmh13
Copy link
Owner

引子

好久没有写while了,突然碰见了一个while(true)的代码,不知道怎么跳出循环了,尴尬...

break和continue

说到break自然会想到continue,都是用来跳出循环的,但是break是跳出整个循环,而continue是跳出当前循环。这里就不细说了。

return

return是来停止函数的。跟breakcontinue压根就不是一类人。如果把return写在while或者for循环中,直接就就是Uncaught SyntaxError: Illegal return statement
例如:

for (var i = 0; i < 5; i++) {
  if (i == 2) {
    return i
  }
}

// Uncaught SyntaxError: Illegal return statement

但是,为什么我们平常经常会在for循环里面用return还没有报错呢?那是因为我们是在function中使用的:

function a() {
  for (var i = 0; i < 5; i++) {
    if (i === 2) {
      return i
    }
  }
}
var bar = a()
console.log(bar) // 2

总结

return 是结束一个函数,并且给出了返回值,从而是函数不再继续执行
breakcontinue退出的语句;break是结束并且跳出语句,continue是停止当前语句,从头开始执行该语句

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

1 participant