如何使用 JavaScript 拆分数组中每个值的最后 n 位数字?

javascriptweb developmentobject oriented programming更新于 2025/10/27 9:16:17

我们有一个像这样的文字数组 −

const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];

我们需要编写一个 JavaScript 函数,该函数接受此数组和一个数字 n,如果相应元素包含大于或等于 n 个字符,则新元素应仅包含最后 n 个字符,否则该元素应保持原样。

让我们来编写该函数的代码 −

示例

const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223,
20191224, 20191225];
const splitElement = (arr, num) => {
   return arr.map(el => {
      if(String(el).length <= num){
         return el;
      };
      const part = String(el).substr(String(el).length - num, num);
      return +part || part;
   });
};
console.log(splitElement(arr, 2));
console.log(splitElement(arr, 1));
console.log(splitElement(arr, 4));

输出

控制台中的输出将是 −

[
   '', 19, 20, 21,
   22, 23, 24, 25
]
[
   '', 9, '0', 1,
   2, 3, 4, 5
]
[
   '', 1219, 1220,
   1221, 1222, 1223,
   1224, 1225
]

相关文章


有用资源