如果if/else中的某些条件匹配,我如何使程序进一步停止执行



var cost=函数(({

if (x.value == "1") {
....
} else if (x.value == ""){
I want my program to stop the execution of any further code here if x.value = empty or null
}
};

我试图在这里返回false。

  • 编程新手

一个封闭的功能范围应该包含在一个函数中,以便按照您想要的方式进行控制。

在函数内部时,您可以使用单词return来决定程序何时结束。

";返回";关键字通常用于使函数向调用方返回一些内容,但这不是强制性的,所以单独使用它,而不返回特定内容是可以的

var cost = function (someParameter) {
if (someParameter==='some value') {
return; // It's returning 'undefined' here, and the function is stopping
} 
const a = 1;
const b = 1;
return a + b;
};

不是,重要的是要注意,除了NodeJS驱动的Javascript程序之外,您不能在该函数范围之外停止整个Javascript。

和许多语言一样,Javascript是基于范围级别的,这意味着您只能控制范围内的内容,而不能控制范围外的内容。

如果你需要该函数之外的逻辑作为采场,那么你也应该在它后面有另一个函数范围

示例:


const functionA = function(paramX){
if(paramX==='foo'){
return true;
}
else {
return false;
}
// this whole thing could be a ternary, though like:
//  return paramX==='foo' 
}

// This one is the one that has the most upper level in the scope chain
const functionB = function(){
let a = 1,
b = 2,
c = 3;
// Negating the function return
// so if the functionA returns false,
// my functionB won't continue execution
if(!functionA(a+b+c===5)){
return;
}
// Now your code can continue to it's purpose because
// functionA returned true
// ...

}
var cost = function () {
if(!x) return;
// do rest of stuff that is necessary if x isn't null | empty
};

要停止函数的执行,只需返回

if (x.value == "1") {
...
} else if (!x.value){
return;
}
};

最新更新