沒想到才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
寫一個高階函式 customLoop 提供類似for陳述式的效果
函式需要一個值,一個測試函式,一個更新函式和一個迴圈主體函式
function customLoop(value, testFunction, updateFunction, bodyLoop) {
if (!testFunction(value)) {
return;
}
bodyLoop(value);
let updatedValue = updateFunction(value);
customLoop(updatedValue, testFunction, updateFunction, bodyLoop);
}
以一個陣列和判斷函式作為參數,寫兩種 customEvery 版本
一個使用 loop
一個使用 some
用函式判斷出一段文字的書寫方向,字元集物件具有direction屬性,屬性有三種 ltr(left to right), rtl(right to left), ttb(top to bottom)