数组变更监听器回调无参数及数组未更新问题排查求助
数组变更监听器异常问题分析与修复
问题1:回调函数无法获取传入参数
原因是重写数组方法时的参数处理逻辑错误:
- 数组方法(如
push)支持传入多个参数,但你重写方法时只用单个arg接收参数,而apply方法需要传入完整的参数数组。调用push时,参数没有被正确传递给回调函数,导致arg始终为undefined。 - 正确做法是用剩余参数
...args接收所有调用时传入的参数,再传递给原数组方法和回调。
问题2:push后数组未更新、写入文件无新元素
核心有两个原因:
- 数组引用被替换:
populateRents中直接给rentCollection赋值了新数组(rentCollection = JSON.parse(rents)),但listenChangesinArray监听的是最初的空数组。新数组没有绑定监听逻辑,后续的push操作不会触发回调,数组变更也不会同步到文件。 - 代码笔误:
writeFile中使用了未定义的bloqsFile,应该改为目标文件rentsFile。
修正后的完整代码
const fs = require('fs'); const rentsFile = __dirname + "/data/rents.json"; export let rentCollection: Rent[] = []; const populateRents = () => { let rents = fs.readFileSync(rentsFile, { encoding: "utf8" }); // 不替换数组引用,清空原数组并添加新元素,保留监听绑定 rentCollection.splice(0, rentCollection.length, ...JSON.parse(rents)); } export const initDb = () => { populateRents(); listenChangesinArray(rentCollection, writeFile); } const listenChangesinArray = (arr: any, callback: any) => { ['pop', 'push', 'reverse', 'shift', 'unshift', 'splice', 'sort'].forEach((m: any) => { const originalMethod = Array.prototype[m]; arr[m] = (...args: any[]) => { // 执行原数组方法,确保数组正常变更 const res = originalMethod.apply(arr, args); // 将参数传递给回调函数 callback.apply(arr, args); return res; } }); } const writeFile = (...args: any[]) => { console.log("Write Args: ", args); // 现在能正确获取参数 try { console.log(JSON.stringify(rentCollection, null, 2)); // 能看到新增元素 fs.writeFileSync(rentsFile, JSON.stringify(rentCollection, null, 2), 'utf8'); console.log('Data successfully saved to disk'); } catch (error) { console.log('An error has occurred ', error); } }
关键修改点说明
- 用
splice更新rentCollection,保留原数组引用,确保监听逻辑始终绑定在目标数组上。 - 重写数组方法时使用
...args接收所有参数,正确传递给原方法和回调函数。 - 修正
writeFile中的文件名错误,确保写入正确的文件。
内容的提问来源于stack exchange,提问作者Zed_Blade
相关产品推荐
相关产品推荐

