我一直對這門課沒有定義,請有人幫助我!我已經嘗試將 this.something 添加到建構式中的幾乎所有內容中,這不應該是必需的,它仍然無法正常作業(那里沒有什么大驚喜......),非常感謝一些幫助!
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);
});
uj5u.com熱心網友回復:
如果映射中不存在鍵,則occurrences()需要回傳0,因為get()會回傳undefined。
occurrences(word) {
// TODO: return the number of occurrences
return this.map1.get(word) || 0;
}
uj5u.com熱心網友回復:
如果 Map 中沒有鍵“hello”,那么 this.map1.get("hello") 將回傳 undefined,而不是 0。
如果您想在沒有發生的情況下收到 0,請修改方法
occurrences(word) {
// TODO: return the number of occurrences
return this.map1.get(word) ?? 0;
}
uj5u.com熱心網友回復:
您提供的測驗用例要求該occurences()函式在找不到匹配項或內部映射為空時回傳 0。
這可以通過回傳 0 來完成,以防找不到匹配項。
例如:
occurrences(word) {
let returnValue=this.map1.get(word)!=undefined ? this.map1.get(word) : 0;
return returnValue;
}
}
uj5u.com熱心網友回復:
它現在正在作業!這是Barmar所說的,我只需要添加|| 0 在發生方法的回傳。非常愚蠢的錯誤。謝謝大家!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494775.html
標籤:javascript 班级
