You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS数组解构异常:为何test函数抛出‘Cannot set property '2' of undefined’错误?

为什么这段JavaScript代码执行时会抛出"Cannot set property '2' of undefined"错误?

嘿,这个问题其实是JavaScript里**自动分号插入(ASI)**的经典坑!咱们一步步拆解来看:

首先先把代码清晰列出来:

const test = () => {
  const arr = [1, 2]
  console.log("any strings") // focus on this line
  [arr[0], arr[1]] = [arr[1], arr[0]]
}
const test1 = () => {
  const arr = [1, 2]
  console.log("any strings"); // add a semicolon will works or comment this line will works too
  [arr[0], arr[1]] = [arr[1], arr[0]]
}
test() // error
test1() // works

错误原因解析

JavaScript有自动分号插入(ASI)机制,会在某些场景下自动给语句补充分号,但它不是万能的——当某一行代码的开头是[、(等符号时,引擎会默认把它和上一行合并成同一个表达式,而不是当作新语句。

在test()函数里,没有分号的那两行被引擎错误地解析成了:

console.log("any strings")[arr[0], arr[1]] = [arr[1], arr[0]]

咱们拆解开看这个错误逻辑:

  • console.log("any strings")执行后返回undefined(因为console.log本身没有返回值)
  • [arr[0], arr[1]]这里用到了逗号运算符,它会依次执行所有表达式,最后返回最后一个的值,也就是arr[1](即2)
  • 于是整个表达式变成了undefined[2] = [arr[1], arr[0]]——你试图给undefined的第2个属性赋值,这显然不合法,所以抛出了Cannot set property '2' of undefined的错误

为什么test1()能正常运行?

在test1()里,要么给console.log语句手动加了分号,明确告诉引擎这是一个完整的独立语句;要么注释掉了那行console.log,让解构赋值的语句单独存在。这两种情况都让引擎正确识别出数组解构交换的操作,自然就能正常执行数组元素的交换了。

内容的提问来源于stack exchange,提问作者郑郑少秋

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:38:46