js中常见的错误类型

    技术2024-05-22  82

    1. SyntaxError:语法错误

    // 1.1 变量名不符合规范 var 1 // Uncaught SyntaxError: Unexpected number var 1a // Uncaught SyntaxError: Invalid or unexpected token // 1.2 给关键字赋值 function = 5 // Uncaught SyntaxError: Unexpected token = //1.3 for if 等语句缺少(){} if(true){ for(var i=0;i<10;i++){ } //Uncaught SyntaxError: Unexpected end of input //1.4使用JSON.parse进行解析json字符串时,解析的内容不合法 JSON.parse(function(){}) //Uncaught SyntaxError: Unexpected token u in JSON at position 1

    2.Uncaught ReferenceError:引用错误

    引用一个不存在的变量时发生的错误。将一个值分配给无法分配的对象

    // 2.1 引用了不存在的变量 a() // Uncaught ReferenceError: a is not defined console.log(b) // Uncaught ReferenceError: b is not defined // 2.2 给一个无法被赋值的对象赋值 console.log("abc") = 1 // Uncaught ReferenceError: Invalid left-hand side in assignment

    3.RangeError:范围错误

    RangeError是当一个只超出有效范围时发生的错误。主要的有几种情况,第一是数组长度为负数,第二是Number对象的方法参数超出范围,以及函数堆栈超过最大值。

    // 3.1 数组长度为负数 [].length = -5 // Uncaught RangeError: Invalid array length // 3.2 Number对象的方法参数超出范围 var num = new Number(12.34) console.log(num.toFixed(-1)) // Uncaught RangeError: toFixed() digits argument must be between 0 and 20 at Number.toFixed // 说明: toFixed方法的作用是将数字四舍五入为指定小数位数的数字,参数是小数点后的位数,范围为0-20. //3.3内存溢出 var num=0; function foo(){ console.log(++num); foo(); } foo(); //Uncaught RangeError: Maximum call stack size exceeded

    4. TypeError类型错误

    变量或参数不是预期类型时发生的错误。

    // 4.1 调用不存在的方法 123() // Uncaught TypeError: 123 is not a function var o = {} o.run() // Uncaught TypeError: o.run is not a function // 4.2 new关键字后接基本类型 var p = new 456 // Uncaught TypeError: 456 is not a constructor // 4.3尝试给undefined和null设置或是访问属性 null.name //Uncaught TypeError: Cannot read property 'name' of null null.age=1 //Uncaught TypeError: Cannot red property 'age' of null undefined.name //Uncaught TypeError: Cannot read property 'name' of undefined undefined.age=1 //Uncaught TypeError: Cannot read property 'name' of undefined // 4.1 调用不存在的方法 123() // Uncaught TypeError: 123 is not a function var o = {} o.run() // Uncaught TypeError: o.run is not a function // 4.2 new关键字后接基本类型 var p = new 456 // Uncaught TypeError: 456 is not a constructor // 4.3尝试给undefined和null设置或是访问属性 null.name //Uncaught TypeError: Cannot read property 'name' of null null.age=1 //Uncaught TypeError: Cannot red property 'age' of null undefined.name //Uncaught TypeError: Cannot read property 'name' of undefined undefined.age=1 //Uncaught TypeError: Cannot read property 'name' of undefined
    Processed: 0.015, SQL: 10