在 JavaScript 中扩展数字
我们需要编写一个函数,该函数将给定一个数字(例如 123)输出一个数组 -
[100,20,3]
基本上,该函数应该返回一个数组,其中包含函数作为参数获取的数字中所有数字的位值。
我们可以使用递归方法来解决这个问题。
因此,让我们来编写此函数的代码 -
示例
代码如下 -
const num = 123;
const placeValue = (num, res = [], factor = 1) => {
if(num){
const val = (num % 10) * factor;
res.unshift(val);
return placeValue(Math.floor(num / 10), res, factor * 10);
};
return res;
};
console.log(placeValue(num));输出
控制台中的输出将是 -
[ 100, 20, 3 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP