JavaScript transformState函数Bug排查:属性移除与清除异常
问题排查与代码修正
核心问题分析
你的代码存在逻辑错误:在处理addProperties和removeProperties动作时,错误地遍历了整个actions数组,而非仅处理当前循环到的单个action。这导致所有添加/移除操作被重复执行,完全打乱了预期的执行顺序:
- 测试1中,已被移除的
hello属性会在后续的add动作中被重新添加; - 测试2中,即使执行过clear操作,之前添加的
yet属性会在后续的add动作中被重新写入state。
修正后的代码
function transformState(state, actions) { for (const action of actions) { switch (action.type) { case 'clear': Object.keys(state).forEach(key => delete state[key]); break; case 'addProperties': Object.assign(state, action.extraData); break; case 'removeProperties': action.keysToRemove.forEach(key => delete state[key]); break; } } return state; }
修正说明
- 针对单个action处理:遍历每个完整的
action对象,确保每次只处理当前动作,而非重复执行所有动作; - 简化逻辑实现:
- 用
switch替代多分支if-else,逻辑更清晰; addProperties用Object.assign直接合并当前action的extraData,简洁高效;removeProperties直接遍历当前action的keysToRemove数组,精准删除指定属性;
- 用
- 移除冗余变量:删除不必要的
transformedState,直接操作传入的state(符合题目要求的直接修改state)。
验证测试用例
测试1执行流程
- 第一个add动作:添加
name和hello,state变为{foo:'bar', bar:'foo', name:'Jim', hello:'world'}; - 第二个remove动作:删除
bar和hello,state变为{foo:'bar', name:'Jim'}; - 第三个add动作:添加
another,最终state为{foo:'bar', name:'Jim', another:'one'},符合预期。
测试2执行流程
- remove动作删除
another,state变为{foo:'bar', name:'Jim'}; - 三次clear动作:state被清空为
{}; - add动作添加
yet,state变为{yet:'another property'}; - clear动作清空state;
- add动作添加
foo和name,state变为{foo:'bar', name:'Jim'}; - remove动作删除
name(hello不存在无影响),最终state为{foo:'bar'},符合预期。
内容的提问来源于stack exchange,提问作者Dukeofduke
相关产品推荐
相关产品推荐

