iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0

沒想到才11天已來到 Chapter 5 的尾聲XD
今天要來寫 Chapter 5 的練習題,有4題

陣列扁平化

結合 reduce 跟 concat 這兩個方法,將陣列扁平化,將一個多維陣列展開為ㄧ維陣列,新陣列內有原始陣列的元素

function customFlatten(arr) {
     return arr.reduce(
         (accumulator, currentValue) => accumulator.concat(currentValue),
         []
     );
}

補充,flatten array 實際上可使用 nameOfArray.flat() 處理即可

nameOfArray.flat(n)
// n => optional,其值為要 flat 的深度,若無填寫表示 n=1

nameOfArray.flat(Infinty)
// 則表示所有nested array 都 flat

自訂 Loop 函式(Your Own Loop)

寫一個高階函式 customLoop 提供類似for陳述式的效果
函式需要一個值,一個測試函式,一個更新函式和一個迴圈主體函式


function customLoop(value, testFunction, updateFunction, bodyLoop) {
    if (!testFunction(value)) {
        return;
    }
    bodyLoop(value);
    let updatedValue = updateFunction(value);
    customLoop(updatedValue, testFunction, updateFunction, bodyLoop);
}

實作 every 函式

以一個陣列和判斷函式作為參數,寫兩種 customEvery 版本
一個使用 loop
一個使用 some

主要書寫方向

用函式判斷出一段文字的書寫方向,字元集物件具有direction屬性,屬性有三種 ltr(left to right), rtl(right to left), ttb(top to bottom)


上一篇
Chapter 5 高階函式-day10
下一篇
Chapter 6 物件的秘密(interface/implementation/method)-day12
系列文
溫故而知新:Eloquent Javascript 閱讀筆記16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言