Word Frequency 计数器
你将构建什么
`wordFrequency(文本)` 函数那个 takes 字符串, 拆分它 到 words, and 返回对象映射每个 word 到它的数量.
学习目标
- 拆分字符串到 words using 字符串方法
- Use 对象 as dictionary (word → 数量)
- 循环 over 数组 and accumulate 数量
- Handle 情况-insensitivity and punctuation
前置要求
- 字符串方法 (拆分, toLowerCase, replace)
- 对象 and 属性 access
- for 循环 or for...的循环
步骤
- 1
Normalize 文本
Convert 文本到 lowercase and 移除 punctuation 所以那个 'Hello!' and 'hello' 是 counted as 相同 word. Use toLowerCase() and regex replace.
代码function wordFrequency(text) { const clean = text.toLowerCase().replace(/[^a-z\s]/g, ''); return clean; }预期结果
wordFrequency('Hello, 世界!') 返回 'hello 世界'.
- 2
拆分到 words
拆分 cleaned 文本 on whitespace 到获取数组的 words. 拆分(' ') 方法 breaks 字符串 at 每个空间.
代码const words = clean.split(' ').filter(w => w.length > 0);预期结果
数组的 individual word 字符串, 否空 字符串.
- 3
数量使用 dictionary 对象
创建空 对象
数量. 循环 over words 数组: for 每个 word, 如果它 exists in 数量, increment; 否则, 设置它 到 1. 对象 acts as word→数量 dictionary.代码const counts = {}; for (const word of words) { if (counts[word]) { counts[word]++; } else { counts[word] = 1; } } return counts;预期结果
wordFrequency(' cat dog') 返回 { : 2, cat: 1, dog: 1 }.
- 4
测试使用 sentence
Call 函数使用 multi-word sentence and print result 到验证数量是 正确.
代码const result = wordFrequency('the quick brown fox jumps over the lazy dog the fox'); console.log(result); // { the: 3, quick: 1, brown: 1, fox: 2, jumps: 1, over: 1, lazy: 1, dog: 1 }预期结果
对象 showing '' appears 3 次数 and 'fox' appears 2 次数.
- 5
添加输入验证
在主逻辑入口处添加输入验证:检查输入是否为有效数字、是否在允许范围内,对非法输入给出清晰提示而非崩溃。这是健壮程序的第一道防线。
代码function validateInput(value, min, max) { if (typeof value !== "number" || Number.isNaN(value)) { throw new Error(`Invalid input: ${value} is not a number`); } if (value < min || value > max) { throw new Error(`Input ${value} out of range [${min}, ${max}]`); } return value; } // Usage const input = validateInput(rawInput, 1, 100);预期结果
非法输入(非数字或超出范围)会抛出清晰的错误信息,合法输入正常通过。
提示
使用 try/catch 包裹调用处,向用户展示友好的错误提示。
自己动手试试
function wordFrequency(text) {
// TODO: normalize, split, count, return object
return {};
}function wordFrequency(text) {
const clean = text.toLowerCase().replace(/[^a-z\s]/g, '');
const words = clean.split(' ').filter(w => w.length > 0);
const counts = {};
for (const word of words) {
counts[word] = (counts[word] || 0) + 1;
}
return counts;
}
console.log(wordFrequency('the quick brown fox jumps over the lazy dog the fox'));你学到了什么
你 used 对象 as dictionary 到 accumulate 数量 — 基本模式 for 分组, tallying, and frequency analysis used in 数据处理.
相关资源
相关练习
- 对象属性 Access 测验
练习 accessing 对象属性.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。