iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0

今天要來寫 Chapter 3 的練習題,共有3題

  1. 寫一個 min 函式接受兩個參數並回傳其中的最小值
    Math.min(numA,numB) 可做到,但暫不要使用它

function min(a, b) {
    if (typeof a === "number" && typeof b === "number") {
        return a > b ? b : a;
    } else {
        console.error("Invalid parameters, need to pass number to compare.");
    }
}
  1. 定義一個遞迴函式 isEven 函式應該接受單一參數(正整數),然後回傳布林值(true/false)
    以數字 50, 75測試,然後看看 -1 時,函式表現行為為何?該如何解決?

先寫出 isEven function..
但發現 -1 會無限往下減下去

function isEven(value) {
    if (typeof value !== "number") {
        console.error("not a valid value");
        return;
    } else {
        if (value - 2 === 0) {
        console.log("is even");
        return;
        }
        if (value - 2 === 1 || value - 2 === -1) {
            console.log("is odd");
            return;
        }
        isEven(value - 2);
    }
}

console.log(isEven(-1)); // 傳 -1 會  Maximum call stack size exceeded

修改 isEven,先將所有傳入的值都先取絕對值,遞迴的值也是傳入絕對值
這樣就沒有正負數的差別了

function isEven(value) {
    let absoluteValue = Math.abs(value);
    if (typeof value !== "number") {
        console.error("not a valid value");
        return;
    } else {
        if (absoluteValue - 2 === 0) {
            console.log("is even");
            return;
        }
        if (absoluteValue - 2 === 1 || absoluteValue - 2 === -1) {
            console.log("is odd");
            return;
        }
        isEven(absoluteValue - 2);
     }
}
  1. 計算字元數 Bean counting
    利用 string[N] 的寫法可以取得字串裡第 N 個字元或字母
    字串裡第一個字元的位置是 0
    字串裡第最後ㄧ個字元的位置是 string.length-1

撰寫一個 countBs 函式,其唯一的參數為一個字串,回傳值是一個數字,表示字串裡有幾個大寫的『 B 』
接著再寫一個 countChar,行為和 countBs 相似,但兩個參數,第二個參數為表示要計算個數的字元


建立新 regex 規則
new RegExp( 字元, "gi" ); g=>globally, i=>不分大小寫

function countChar(tagetString , char){
    const regexRule = new RegExp(char , "g");
    let nmberOfChar = tagetString.match(regexRule);
    if(nmberOfChar){
        return nmberOfChar.length;
    }else{
        return console.error("There's no matching character in the string.")
    }
}

那麼明天就要進入 Chapter 4 囉~


上一篇
Chapter 3 函式 Function_2(Closure/Recursive)-day5
系列文
溫故而知新:Eloquent Javascript 閱讀筆記6
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言