Mr.Mou @ ShiShi AP Center

离线救急 用 Chrome Console 跑 CodeHS 代码

为什么要学这一招?(没网/平台卡顿也能写代码)

同学们:当你们的 CodeHS 网络不稳定时,可以用 Chrome DevTools Console 临时测试 while 循环、if、变量更新等逻辑。

关键点:CodeHS 里的 readLine / readInt / readFloat / println 这些是平台提供的函数,浏览器默认没有,所以我们需要在 Console 顶部先贴一段“辅助函数(helper functions)”。


Step 1:打开 Console(每次离线测试都要会)


Step 2:先复制粘贴“辅助函数”到 Console 顶部(必做)

把下面整段代码 一次性复制,粘贴到 Console,回车执行。之后你就可以像在 CodeHS 一样写 readLine/readInt/readFloat/println 了。

/* ================================
CodeHS -> Chrome Console 辅助函数
使用方法:先粘贴本段,再写/粘贴你的代码
================================ */

// 1) 输入:字符串
function readLine(msg){
return prompt(msg);
}

// 2) 输入:整数(自动转 Number,再做取整)
function readInt(msg){
return Math.trunc(Number(prompt(msg)));
}

// 3) 输入:小数
function readFloat(msg){
return Number(prompt(msg));
}

// 4) 输出:对应 CodeHS 的 println
function println(msg){
console.log(msg);
}

// 5) 打印空行:println("") 在 Console 一样有效
//    示例:println("");

注意:prompt() 在浏览器里弹出输入框;你输入的内容会返回给程序使用。


Step 3:Console 测试代码的“黄金规则”(避免踩坑)

规则 A:Console 不会自动运行 start()(你要自己调用)

在 CodeHS 里平台会自动调用 start(),但在 Console 里不会。你有两种做法:

示例(推荐写法):

function start(){
println("Hello from start()");
}

start(); // Console 里必须手动调用

规则 B:prompt 输入的是“字符串”,readInt/readFloat 才会转成数字

常见错误:字符串拼接导致结果不对,例如 "2" + "3" 变成 "23"。


规则 C:无限循环会“卡死页面”,别慌,刷新就好

如果 while 条件永远为真,Console 可能卡住:


规则 D:重复运行代码时,可能出现“变量已声明”报错

Console 会记住你之前声明过的 let 变量。你再次粘贴同一段代码,可能报错:

Identifier 'x' has already been declared

解决办法(按推荐顺序):


Console 实用技巧(让你写代码更舒服)

技巧 1:清屏(保持窗口干净)

console.clear();

你可以在开始测试前先清屏,输出更清楚。


技巧 2:调试 while 循环(观察变量有没有变化)

当你怀疑循环不会停或 total 变成 NaN,就把变量打印出来:

console.log("num =", num, "total =", total);

调试核心问题就两个:


技巧 3:快速测试一小段逻辑(不用整份代码)

Console 允许你一段一段试。比如先试输入和比较:

let x = readInt("输入一个数字:");
println("你输入的是 " + x);
println(x > 10);

示例 1:C1 Sum Until 0(Console 可运行版)

规则:不停输入数字,输入 0 停止,输出总和。

function start(){
let total = 0;
let num = readInt("What is the number?");

```
while(num != 0){
    total = total + num;
    num = readInt("What is the number?");
}

println("total is " + total);
```

}

start();

示例 2:C2 Password Checker(Console 可运行版)

规则:密码是 coffee,输错就一直重输,直到正确。

function start(){
let CORRECT_PASSWORD = "coffee";
let inputPassword = readLine("What is the password?");

```
while(inputPassword != CORRECT_PASSWORD){
    inputPassword = readLine("Wrong password. Try again:");
}

println("Access granted");
```

}

start();

最后提醒(考试/作业都通用)

把这篇收藏好:网不稳的时候,你依然能把逻辑写出来、跑出来、改出来。