在 JavaScript 中扩展数字

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/3 18:20:17

我们需要编写一个函数,给定一个数字,例如 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 ]

相关文章


有用资源