5

JavaScript报错类型(报错速查)

 2 years ago
source link: https://segmentfault.com/a/1190000041420674
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1. syntaxError 语法错误

  • 变量名不规范:
    var 1 = 1; // Uncaught SyntaxError: Unexpected number
    var 1a = 1; // Uncaught SyntaxError: Invalid or unexpected number
  • 关键字赋值:
    new = 1; // Uncaught SyntaxError: Unexpected token =
  • 基本语法错误:
    var a = 5: // Uncaught SyntaxError: Unexpected token :

2. ReferenceError 引用错误

  • 变量或者函数未被声明:
    fn(); // Uncaught ReferenceError: fn is not defined
  • 给无法被赋值的对象赋值时:
    console.log() = 2; // Uncaught ReferenceError: Invalid left-hand side in assignment

3. RangeError 范围错误

  • 数组长度赋值为负数:
    var arr = [1, 2, 3];
    arr.length = -1; // Uncaught RangeError: Invalid array length
  • 对象方法参数超出可行范围
    var num = 66.66;
    num.toFixed(-1); // Uncaught RangeError: toFixed() digits argument must be between 0 and 100

4. TypeError 类型错误

  • 调用不存在的方法:
    123(); // Uncaught TypeError: 123 is not a function
    // 会先判断是否可能是函数,像123就不可能是函数,所以直接报类型错误,而如果是合法的函数名,则报ReferenceError
    var obj = {}
    obj.say(); // Uncaught TypeError: obj.say is not a function
  • 实例化原始值:
    var a = new 1; // Uncaught TypeError: 1 is not a constructor

5. URIError URI错误

URI: URIFORM RESOURCE IDENTIFIER  统一资源标识符
URL: URIFORM RESOURCE LOCATOR  统一资源定位符
URN: URIFORM RESOURCE NAME  统一资源标识符

URI包括URL和URN

decodeURI("%abc"); // Uncaught URIError: URI malformed

6. EvalError eval函数执行错误


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK