如何'return'从父函数'
How to 'return' out of a parent function from it's child?
我经常在项目中使用verifyInput函数来确保从用户那里获得有效的输入。不时地,我发现自己希望能够从verifyInput中退出父函数。verifyInput通常给定一个prompt()
函数。提示,有取消键。如果单击cancel,我想退出嵌套表达式。我该怎么做呢?
function verifyInput(foo, value){
const input = foo();
if (!isNaN(input) && !input || input === null || input === undefined){
if(input === null){
/*The input is null, because they hit the cancel button. I should exit myLoop here.*/
} else {
alert("Not valid.");
}
return verifyInput(foo,value);
} else {
if(value && input.search(value) < 0){
alert("'"+[input]+"' is not a valid input.");
return verifyInput(foo,value);
}else{
return input;
}
}
}
function myFunc(){
var myInput = verifyInput( () => prompt("What is your input?"));
alert(myInput);
return myFunc();
}
myFunc();
没有办法直接从verifyInput
停止调用者(myLoop
)的执行,除非抛出异常。
正如其他人所说,您可以检查myLoop
的返回值以有条件地停止它。
但也许一个更干净的解决方案是使用回调,它只会在输入不是"exit"
时被调用。如果输入有效,这个回调将负责获取输入,并再次调用myFunc
以继续循环。例子:
function verifyInput(prompter, callback) {
var value = prompter()
if (value === "exit") {
return // don't proceed with the callback if `value` is "exit"
}
if (invalid(value)) { // function to be implemented
alert("invalid")
return verifyInput(prompter, callback)
}
callback(value)
}
function myFunc() {
var prompter = () => prompt("What is your input?")
verifyInput(prompter, (value) => {
console.log(value) // logs the input
myFunc()
})
}
myFunc()
小提琴:https://jsfiddle.net/guisehn/r1Lwxkhp/
相关文章:
- 函数在return语句之前返回空对象
- Javascript用函数return替换局部变量
- JavaScript:return WebForm_FireDefaultButton();这个函数在做什么,我该如何复
- return语句在JavaScript中使用而不中断函数
- 在 JavaScript 中使用 return 作为函数的原因是什么?
- 了解 in return 函数中的增量运算符
- 如何将 ** return (this.innerText.length <= 200) ** 移动到函数
- 函数() { return false; } 的操作细节().
- Backbone.model:对象函数 (a){return new n(a)} 没有方法 'has'
- 为什么我的子函数需要“return”语句以避免出错?父函数没有“返回”,也没有错误
- 为什么“return”不完全停止“if”语句中的函数
- 调用“done()”和在函数完成执行后调用“return”有什么区别
- Requirejs带有Knockout错误:无法处理绑定“;组件:函数(){return f}"-匿名定义()
- 我试图在代码学院学习javascript,有人可以解释这个函数末尾“return 1;”的目的
- “return”关键字在“forEach”函数中是什么意思
- 创建一个函数为RETURN的变量,然后将其放入第二个变量中
- 为什么一些角$scope函数"return&;一个操作
- Javascript函数"return this"不工作
- Javascript子函数将return传递给父函数return
- JS.对象函数Return中的返回函数