将数字转换为十位、百位、千位等 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 21:00: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 ]

相关文章


有用资源