我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。
当前回答
带有函数的Wrapp
(function(){
alert('start')
return;
alert('no exec')
})
其他回答
要停止脚本执行而不出现任何错误,可以将所有脚本包含到函数中并执行它。 这里有一个例子: (函数(){ console.log(一); 返回; console.log(两个); }) ();
上面的脚本将只记录一个日志。
在使用前
如果您需要在脚本本身之外读取脚本的函数,请记住(通常)这是行不通的:要做到这一点,您需要使用一个预先存在的变量或对象(您可以将函数放在窗口对象中)。 上面的代码可能是你不想要的:将整个脚本放在一个函数中可能会产生其他后果(例如,这样做,脚本将立即运行,并且没有办法从浏览器开发中修改其部分,正如我所知道的,在Chrome中)
If you're looking for a way to forcibly terminate execution of all Javascript on a page, I'm not sure there is an officially sanctioned way to do that - it seems like the kind of thing that might be a security risk (although to be honest, I can't think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just return from whatever function is executing. (The return statement is optional if it's the last thing in the function and the function shouldn't return a value) If there's some reason returning isn't good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.
注意,在实践中,大多数浏览器的Javascript解释器在遇到错误时会简单地停止运行当前脚本。所以你可以做一些事情,比如访问一个未设置变量的属性:
function exit() {
p.blah();
}
它可能会中止脚本。但你不应该指望它,因为它根本不是标准的,而且它看起来真的是一个糟糕的做法。
编辑:好吧,也许这不是一个很好的答案Ólafur的光。尽管他链接到的die()函数基本上实现了我的第二段,即它只是抛出一个错误。
"exit"函数通常退出程序或脚本,并以错误消息作为参数。例如php中的die(…)
die("sorry my fault, didn't mean to but now I am in byte nirvana")
在JS中等效的是用throw关键字发出错误信号,如下所示:
throw new Error();
你可以很容易地测试这个:
var m = 100;
throw '';
var x = 100;
x
>>>undefined
m
>>>100
在JavaScript中有多种方式,下面是其中的一些
方法1:
throw new Error("Something went badly wrong!");
方法2:
return;
方法3:
return false;
方法4:
new new
方法5:
使用上述方法编写自定义函数,并在需要的地方调用
注意: 如果您想暂停代码执行,您可以使用
debugger;
带有函数的Wrapp
(function(){
alert('start')
return;
alert('no exec')
})
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?