JavaScript错误类型

本文深入解析JavaScript中的六种常见错误类型:语法错误(SyntaxError)、引用错误(ReferenceError)、范围错误(RangeError)、类型错误(TypeError)、URL错误(URLError)及eval错误(EvalError),并提供具体实例帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

处理代码错误的核心,首先要知道代码里面会发生什么错误

JavaScript错误类型:

  • SyntaxError(语法错误)
  • ReferenceError(引用错误)
  • RangeError(范围错误)
  • TypeError(类型错误)
  • URLError(URL错误)
  • EvalError(eval错误)

SyntaxError(语法错误)

解释代码时发生的语法错误

var 1a; // 语法错误,javascript变量首位字符,必须是字母或者下划线
// Uncaught SyntaxError: Invalid or unexpected token

var delete = 1; // 语法错误,javascript变量名不能是保留字段
// Uncaught SyntaxError: Unexpected token 'delete'

ReferenceError(引用错误)

// 引用了一个不存在的变量
function foo(a) {
return a + b;
}
foo(2)
/*
Uncaught ReferenceError: b is not defined
    at foo (<anonymous>:2:12)
    at <anonymous>:4:1
*/

RangeError(范围错误)

new Date('2014-25-23').toISOString();
/*
Uncaught RangeError: Invalid time value
    at Date.toISOString (<anonymous>)
    at <anonymous>:1:24
*/

TypeError(类型错误)

undefined.bar; // // 错误类型: undefined没有这个属性
/*
Uncaught TypeError: Cannot read property 'bar' of undefined
    at <anonymous>:1:11
*/

URLError(URL错误)

decodeURIComponent('%');
/*
Uncaught URIError: URI malformed
    at decodeURIComponent (<anonymous>)
    at <anonymous>:1:1
*/

EvalError(eval错误)

  throw new EvalError('Hello', 'someFile.js', 10);
/*
Uncaught EvalError: Hello
    at <anonymous>:1:9
*/

参考文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值