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

Vue中调用splice删除一个数组元素后另一个同源数组也被修改是什么原因

问题原因

数组是JS中的引用类型,你在initData中直接将同一个response赋值给arrayA和arrayB时,两个变量实际指向内存中的同一份数组对象,无论操作哪一个变量修改数组内容,本质都是修改同一份数据,因此两个数组会同步变动。

解决方案

赋值时对数组做拷贝生成独立的新数组即可,根据业务场景可选择浅拷贝或深拷贝:

  • 若数组元素为基础类型,或后续无需修改数组内的对象属性,使用浅拷贝即可,修改initData的赋值逻辑:
async initData() {
    const { data: response } = await this.$store.dispatch("getData", { id: this.$route.params.id })
    // 浅拷贝方式1:展开运算符
    this.arrayA = [...response]
    this.arrayB = [...response]
    // 浅拷贝方式2:Array.from (二选一即可)
    // this.arrayA = Array.from(response)
    // this.arrayB = Array.from(response)
}
  • 若后续需要修改数组内的对象属性,且要求两个数组的改动互不影响,使用深拷贝:
async initData() {
    const { data: response } = await this.$store.dispatch("getData", { id: this.$route.params.id })
    // 普通场景可直接用JSON序列化反序列化实现深拷贝
    this.arrayA = JSON.parse(JSON.stringify(response))
    this.arrayB = JSON.parse(JSON.stringify(response))
    // 若有特殊类型(如函数、Symbol、BigInt等),可使用项目内置的深拷贝工具实现
}

内容的提问来源于stack exchange,提问作者Morgan Millet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:12:02