如何在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 ]
广告
数据结构
网络工程
关系型数据库管理系统
操作系统
Java
iOS
超文本标记语言
层叠样式表
安卓
Python
C语言
C++
C#
MongoDB
MySQL
JavaScript
PHP