【发布时间】:2021-08-27 20:02:21
【问题描述】:
假设我有一个获取随机数的函数,然后返回该数字是否满足条件,如果不满足则抛出错误:
const randFunc = () => {
let a = Math.floor(Math.random() * 10)
if(a === 5){
return a
} else {
throw new Error('Wrong Num')
}
}
我想知道的是我是否可以循环这个函数直到我得到'5'
try {
randFunc()
} catch {
//if error is caught it re-trys
}
谢谢!
【问题讨论】:
-
把它放到一个循环中。
标签: javascript function loops error-handling try-catch