是否可以从函数中断执行程序,或者我需要检查boolean val返回?
代码
function check(something) {
if (!something) return;
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");
答案 0 :(得分:1)
一种方法是通过Error,否则你需要使用布尔检查,是的。我建议使用布尔值
function check(something) {
if (!something) throw "";
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");
答案 1 :(得分:0)
...最简单
(function(){
function check(something) {
if (!something) return false;
// Else pass and program continuing
}
if(!check(false)) return;
alert("hello");
});
(function(){ ... });
被称为IIFE立即调用的函数表达式。
答案 2 :(得分:0)
将您的代码放入IIFE,然后您可以使用return
(function() {
function check(something) {
if (!something) {
return false;
} else {
return true;
}
}
if (!check(false)) {
return;
}
alert("hello");
});