简体   繁体   English

警报返回未定义(js)

[英]alert returns undefined (js)

I am learning errors in js and I have came up with the following code:我正在学习 js 中的错误,我想出了以下代码:

function StartGame() {
  try {
   if (input.value == "") {throw alert("Complete blanks"); return false}
   if (!input.value.match(/^[A-Za-z]+$/)) {throw alert("Only letters allowed"); return false}
   if (input.value.length < 3) {throw alert("Must have at least 3 characters"); return false}}
   catch(errorAlert) {alert(errorAlert)}
  inputPanel.style.display = "none"

  ... //some code 
 }

let inputPanel = document.querySelector("#form")
let input = document.querySelector("#input") 

<form id="form" title="Write your name"> <label> Enter your username: </label>
   <input id="input" type="text" maxlength="10" autofocus>
   <button type="button" onclick="StartGame()" id="begin-game"> Submit </button>
  </form>

However, when throw event occurs (so when input is not properly submitted), first comes the alert (that is normal) BUT then, another alert appears saying "undefined" and returns the rest of the code true (the rest of the code runs).但是,当抛出事件发生时(因此当输入未正确提交时),首先出现警报(这是正常的)但是,然后出现另一个警报,说“未定义”并返回其余代码为真(其余代码运行)。 Instead, I would like that when input is not properly validated, there are no undefined alerts and it returns false.相反,我希望当输入未正确验证时,没有未定义的警报并且它返回 false。 Any help please?请问有什么帮助吗? Thanks谢谢

This is because of your throw keyword.这是因为你的throw关键字。 Quoting MDN:引用 MDN:

The throw statement throws a user-defined exception. throw 语句抛出用户定义的异常。 Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack.当前函数的执行将停止(不会执行 throw 之后的语句),并将控制权传递给调用堆栈中的第一个 catch 块。 If no catch block exists among caller functions, the program will terminate.如果调用者函数之间不存在 catch 块,则程序将终止。

You can read more about it here .您可以在此处阅读更多相关信息。

Also as other users pointed out, you should throw an Error, not an alert同样正如其他用户指出的那样,您应该抛出错误,而不是警报

You need to throw the message and then alert it inside the catch block.您需要抛出消息,然后在 catch 块中提醒它。 When you put a function in an throw statement, the function will be executed and the return value will be thrown.当你将一个函数放入 throw 语句时,该函数将被执行并抛出返回值。

 try{ // Do something that throws a message throw "Something messed up!"; }catch(message){ // Alert the message here alert(message); }

However, it's a much better idea to throw an Error object instead, as it contains helpful information for debugging purposes.然而,抛出一个Error对象是一个更好的主意,因为它包含用于调试目的的有用信息。

 try{ // do something that throws an error throw new Error("Something screwed up!"); }catch(e){ // alert the message here alert(e.message); // The error object also has other features // that make it helpful for debugging, like the stack trace console.log(e.stack); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM