From 13bc50eb7e394e86722c2c9aba10bd2865114de1 Mon Sep 17 00:00:00 2001 From: Jaydon Date: Fri, 24 Jul 2026 03:57:54 +0800 Subject: [PATCH] docs(js_notes): keep improved repeat (edge case), comment out old versions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - F: user improved repeat to check times===0 BEFORE fn() so repeat(fn,0) prints 0 times; keep it live, comment the two earlier versions as ❌ contrast (never leave duplicate live const → SyntaxError) - my-mistakes M: add re-occurrence context (new version written but old not deleted → duplicate const) --- js_notes/00-concepts/my-mistakes.md | 5 ++++- js_notes/10-functions.js | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/js_notes/00-concepts/my-mistakes.md b/js_notes/00-concepts/my-mistakes.md index 9ce9827..6d6cf81 100644 --- a/js_notes/00-concepts/my-mistakes.md +++ b/js_notes/00-concepts/my-mistakes.md @@ -124,12 +124,15 @@ describe: function () => {...} // ❌ 语法错:function 和 => 不能同时 ## M. const 同名声明两次 -📍来源:`../07-objects/practice.js` 练习 D +📍来源:`../07-objects/practice.js` 练习 D;又见 `../10-functions.js` 练习 F ```js const student = {...} const student = {...} // ❌ Identifier 'student' has already been declared ``` - **教训**:同作用域 `const` 不能重名;想留"错误对照"就**注释掉**旧的,别当活代码。 +- **重演情境(10章F)**:迭代改进时【新写了一版更好的 `const repeat`,却忘了删/注释掉旧版】 + → 两个活的 `const repeat` → 整个文件直接报错跑不了。 + 改进代码时:**旧版要么删,要么注释成 ❌ 对照,绝不能两个都当活代码**。 ## N. 以为"代码块能算出值、会自动返回"⭐⭐(概念推错,非手滑) diff --git a/js_notes/10-functions.js b/js_notes/10-functions.js index 7e2d408..afc6b02 100644 --- a/js_notes/10-functions.js +++ b/js_notes/10-functions.js @@ -251,15 +251,28 @@ console.log(triple(7)) // 提示:times 次 → 用循环;fn 是"传进来的函数",直接 fn() 就能调用 const fn = () => {console.log("执行一次fn函数")} + +// ❌ 最初版:把 repeat 和 fn 搞混,fn(fn, times-1) —— fn 不会递归,只执行一次 // const repeat = (fn, times) => { // if (times === 0) return // return fn(fn, times -1) // } + +// ❌ 第二版:fn() 在前、判断在后 —— 能跑,但 repeat(fn, 0) 会先打印再停 = 打印 1 次(边界错) +// const repeat = (fn, times) => { +// fn() +// times -= 1 +// if (times === 0) return +// repeat(fn, times) +// } + +// ✅ 终版:判断在前 → repeat(fn, 0) 直接返回,打印 0 次(边界正确) const repeat = (fn, times) => { + if (times === 0) return // 先判断:times 为 0 就不打印(edge case 处理对) fn() times-=1 - if (times === 0) return // return repeat(fn, times) - repeat(fn, times) + repeat(fn, times) // 不需要 return 也行(不需要返回值) } + repeat(fn, 3) \ No newline at end of file