catch javascript 的意外令牌错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32081507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:49:48  来源:igfitidea点击:

unexpected token error for catch javascript

javascripttry-catch

提问by Imo

I am banging my head trying to find the error in this code. I have checked it so many times can someone point out where the problem is?

我正在努力寻找这段代码中的错误。我已经检查了很多次,有人能指出问题出在哪里吗?

$(function() {
  try {
    function endswith(str, ends) {
      if (ends === '') return true;
      if (str == null || ends == null) return false;
      str = String(str);
      ends = String(ends);
      return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
    }
    var referrer = new URL(document.referrer).domain;
    if (endswith(referrer, "xyz.com")) {
      $(".logo .logo-external").remove();
    } else {
      $(".logo .logo-internal").remove();
    }
  } catch () {}
});

回答by joyBlanks

catch (e) {}You missed the variable e

catch (e) {}你错过了变量 e

$(function() {
  try {
    function endswith(str, ends) {
      if (ends === '') return true;
      if (str == null || ends == null) return false;
      str = String(str);
      ends = String(ends);
      return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
    }
    var referrer = new URL(document.referrer).domain;
    if (endswith(referrer, "xyz.com")) {
      $(".logo .logo-external").remove();
    } else {
      $(".logo .logo-internal").remove();
    }
  } catch (e) {}
});

回答by themefield

As per MDN, try...catchsyntax is defined similar to the following:

根据MDNtry...catch语法定义类似于以下内容:

try {
   try_statements
}
...
[catch (exception_var) {
   catch_statements
}]
[finally {
   finally_statements
}]

This means the exception_varis NOT optional. Otherwise, it would look like this:

这意味着exception_var不是可选的。否则,它看起来像这样:

...
[catch ([exception_var]) {     // Uncaught SyntaxError: Unexpected token )
   catch_statements
}]
...