最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

unexpected token error for catch javascript - Stack Overflow

programmeradmin1浏览0评论

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")) {
      $(".logo .logo-external").remove();
    } else {
      $(".logo .logo-internal").remove();
    }
  } catch () {}
});

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 () {}
});
Share Improve this question edited Aug 18, 2015 at 19:55 Barmar 781k56 gold badges545 silver badges659 bronze badges asked Aug 18, 2015 at 19:54 ImoImo 1,4754 gold badges30 silver badges57 bronze badges 2
  • You need a variable name inside the catch() parentheses. – Barmar Commented Aug 18, 2015 at 19:56
  • Also see: Can I use a try/catch in JavaScript without specifying the catch argument/identifier? – sleske Commented Jun 14, 2021 at 8:42
Add a comment  | 

2 Answers 2

Reset to default 13

catch (e) {} You missed the variable 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) {}
});

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

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

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

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

评论列表(0)

  1. 暂无评论