在JavaScript中有像“死亡”这样的东西吗?我试过使用"break",但不起作用:)
发布于 2009-09-02 01:57:43
如果标记了块作用域,则只能对其进行break
。例如:
myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
不能从作用域中的函数中中断块作用域。这意味着你不能做像这样的事情:
foo: { // this doesn't work
(function() {
break foo;
}());
}
不过,您可以对函数执行类似的操作:
function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
发布于 2009-09-01 11:32:11
throw new Error("my error message");
发布于 2011-11-04 22:09:11
您可以简单地使用return;
示例
$(document).ready(function () {
alert(1);
return;
alert(2);
alert(3);
alert(4);
});
返回将返回到主调用方函数test1();并从那里继续返回到test3();
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
test2();
test3();
}
function test2(){
alert(2);
return;
test4();
test5();
}
function test3(){
alert(3);
}
function test4(){
alert(4);
}
function test5(){
alert(5);
}
test1();
</script>
</body>
</html>
但是如果你只是添加了throw‘’,这将会完全停止执行而不会导致任何错误。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
test2();
test3();
}
function test2(){
alert(2);
throw '';
test4();
test5();
}
function test3(){
alert(3);
}
function test4(){
alert(4);
}
function test5(){
alert(5);
}
test1();
</script>
</body>
</html>
这在firefox和chrome上进行了测试。我不知道IE或Safari是如何处理的
https://stackoverflow.com/questions/1361437
复制相似问题