新手在這里有一些丑陋的代碼。我仍在研究方法封裝。我正在嘗試撰寫允許我比較兩個輸入字串并回傳其“字謎”狀態的布林值的代碼,條件如下所示。如果有人能為我提供“函式缺少結束回傳陳述句并且回傳型別不包括未定義”的解決方案或解決方法,我將不勝感激。歡迎和贊賞任何建議。提前致謝!
class Example {
firstWord = prompt();
secondWord = prompt();
public isAnAnagram(firstWord: string, secondWord: string): boolean {
if (firstWord && secondWord !== null) {
const firstArray = firstWord.split("");
const secondArray = secondWord.split("");
// Show how the firstword and secondword have transformed into arrays
console.log(firstArray, secondArray);
let arrayPassed = true;
if (
firstArray.every((w) => secondArray.includes(w)) &&
secondArray.every((w) => firstArray.includes(w))
) {
// Show if first word passes anagram test through console
console.log("Found all letters of " firstWord " in " secondWord);
} else {
arrayPassed = false;
// Show if first word does not pass anagram test through console
console.log(
"Did not find all letters of " firstWord " in " secondWord
);
}
return arrayPassed;
}
}
}
uj5u.com熱心網友回復:
您通過檢查以下內容開始您的功能:
if (firstWord && secondWord !== null) {
if 中的代碼回傳一個布林值,但沒有else塊,也沒有if. 因此,如果代碼與 不匹配if,您將隱式回傳undefined. 這與您告訴 typescript 的回傳型別相矛盾:boolean。
public isAnAnagram(firstWord: string, secondWord: string): boolean
要解決此問題,請添加一個else案例并回傳一個布林值:
else {
return false
}
或者更改回傳型別以允許您回傳undefined。
public isAnAnagram(firstWord: string, secondWord: string): boolean | undefined
uj5u.com熱心網友回復:
您可以在回傳之前嘗試使用 try catch。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451840.html
上一篇:為什么是這個數字型別?(打字稿)
