在类中使用new Map()计数数组中的出现次数时未定义



我一直没有定义这个类,请有人帮助我!我试过添加这个。构造函数中几乎所有的东西,不应该是必要的,它仍然不能工作(没有什么大的惊喜…),真的很感谢一些帮助!

class Counter {
constructor(text) {
// TODO: build an internal Map of word => occurrences.
this.text = text;
const textArray = this.text.split(" ");
const count = {};
for (const word of textArray) {
if (count[word]) {
count[word] += 1;
} else {
count[word] = 1;
}
}
this.map1 = new Map();
for (const word of textArray) {
this.map1.set(word, count[word]);
}
}

occurrences(word) {
// TODO: return the number of occurrences
return this.map1.get(word);
}
}

错误:

Should be case-insensitive
expect(received).toBe(expected)

Expected value to be (using ===):
1
Received:
undefined

Difference:

Comparing two different types of values. Expected number but received undefined.

at Object.<anonymous> (__tests__/01_counter.test.js:9:40)
at new Promise (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5

,下面是测试:

test("Should be case-insensitive", () => {
const counter = new Counter("Lorem ipsum dolor sit amet, consectetur adipisicing elit");
expect(counter.occurrences("lorem")).toBe(1);
});

如果映射中不存在键,则occurrences()需要返回0,因为get()将返回undefined

occurrences(word) {
// TODO: return the number of occurrences
return this.map1.get(word) || 0;
}

如果没有关键字"hello"在Map中,this.map1.get("hello")将返回undefined,而不是0。

如果您希望在没有发生的情况下接收0,请修改方法

occurrences(word) {
// TODO: return the number of occurrences
return this.map1.get(word) ?? 0;
}

您提供的测试用例要求occurences()函数在没有找到匹配或内部映射为空的情况下返回0。

如果找不到匹配项,可以通过返回0来实现。

例如:

occurrences(word) {
let returnValue=this.map1.get(word)!=undefined ? this.map1.get(word) : 0;
return returnValue;
}

}

虽然测试文本断言Counter.occurrences不区分大小写,但事实并非如此。检查counter.occurrences("Lorem")的值,您将得到1。简而言之,测试正在做它的工作,提醒您注意错误。

Counter中没有实现不区分大小写的匹配。这样做,测试将被清除。如何实现不区分大小写是一个练习,特别是当这似乎是一个赋值时。

注意你也应该有一个测试来断言其他情况,例如expect(counter.occurrences("Lorem")).toBe(1);

最新更新