如何将系列数据存入指定对象?onCountChange函数运行异常修复求助
问题根源&修复方案
你的代码存在多个语法和逻辑错误,直接触发运行时异常导致函数终止、数据写入失败,具体问题和修改方式如下:
- 错误1:rate_code/rate_type变量定义完全错误
你声明变量时直接用未赋值的rate_code作为key取值,既没有把这两个值作为函数入参传入,还错误把变量赋值为数组元素(你需要的是键名不是键对应的值)。首先需要给onCountChange函数补传rate_code、rate_type两个入参,或者从当前选中状态中读取正确的键名。 - 错误2:错误覆写全局存储对象导致原有数据丢失
this.arrSelection.main = {room_index};和this.arrSelection.rates = {stateroom_index};两行直接把原有存储对象替换为只有单个属性的新对象,原本的main.rates路径被直接清空,后续写入自然无效。 - 错误3:嵌套对象未逐层初始化就直接赋值
你直接访问this.arrSelection.main.rates[rate_code][rate_type],如果rate_code对应的对象不存在,访问二级rate_type会直接抛出Cannot set properties of undefined异常,导致函数直接终止。 - 错误4:赋值时混淆变量和静态属性名
你写的this.arrSelection.main.rates.rate_code是读取rates下名为rate_code的静态属性,不是读取rate_code变量对应的属性值,取值永远为undefined。
修复后代码
// 函数入参补传rate_code、rate_type onCountChange(action, room_index, stateroom_index, rate_code, rate_type) { // 1. 先逐层初始化存储对象,避免undefined异常 if (!this.arrSelection.main) this.arrSelection.main = {} if (!this.arrSelection.main.rates) this.arrSelection.main.rates = {} // 初始化rate_code对应的对象 if (!this.arrSelection.main.rates[rate_code]) { this.arrSelection.main.rates[rate_code] = {} } // 2. 写入目标数据,不要覆写原有main对象 this.arrSelection.main.rates[rate_code][rate_type] = { main: room_index, rates: stateroom_index, rate_code: rate_code, rate_type: rate_type } let roomAdultCount = this.getRoomAdultCount(room_index, stateroom_index) let roomChildCount = this.getRoomChildCount(room_index, stateroom_index) if (!action && (roomAdultCount !== 0 || roomChildCount !== 0)) { this.minusUnitCount(room_index, stateroom_index); this.minusRoomChildCount(room_index, stateroom_index); this.minusRoomAdultCount(room_index, stateroom_index); this.minusStateroomRoomAdultChildCount(room_index, stateroom_index); this.minusRoomAccomCount(room_index, stateroom_index); } if (action) { this.addUnitCount(room_index, stateroom_index); this.addRoomChildCount(room_index, stateroom_index); this.addRoomAdultCount(room_index, stateroom_index); this.addStateroomRoomAdultChildCount(room_index, stateroom_index); this.addRoomAccomCount(room_index, stateroom_index); } this.appendChargeMethod(stateroom_index) this.updateSegmentOneStatus(room_index, stateroom_index) this.buildBookingSummaryRoomArr() this.shouldResetAddons() }
内容的提问来源于stack exchange,提问作者Kai
相关产品推荐
相关产品推荐

