如何在JavaScript中將數字陣列拆分為單個數字?
我們有一個數字字面量陣列,我們需要編寫一個函式,如splitDigit(),它接受此陣列並返回一個數字陣列,其中大於10的數字被拆分為單個數字。
例如:
//if the input is: const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ] //then the output should be: const output = [ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1, 0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ];
所以,讓我們編寫此函式的程式碼,我們將使用Array.prototype.reduce()方法來拆分數字。
示例
const arr = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 ] const splitNum = (n, res = []) => { if(n){ return splitNum(Math.floor(n/10), [n % 10].concat(res)); }; return res; }; const splitDigit = (arr) => { return arr.reduce((acc, val) => acc.concat(splitNum(val)), []); }; console.log(splitDigit(arr));
輸出
控制檯中的輸出將為:
[ 9, 4, 9, 5, 9, 6, 9, 7, 9, 8, 9, 9, 1, 0, 0, 1, 0, 1, 1, 0, 2, 1, 0, 3, 1, 0, 4, 1, 0, 5, 1, 0, 6 ]
廣告