在 JavaScript 中拆分数组中每个值的最后 n 位数字
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/12 17:48:17
我们有一个像这样的文字数组 −
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
我们需要编写一个 JavaScript 函数,该函数接受此数组和一个数字 n,如果相应元素包含大于或等于 n 个字符,则新元素应仅包含最后 n 个字符,否则该元素应保持原样。
因此,如果 n = 2,对于此数组,输出应该是 −
const output = [68, 65, 67, 3, 78, 78, 35, 99];
示例
以下是代码 −
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
const splitLast = (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(splitLast(arr, 2));
输出
这将在控制台中产生以下输出 −
[ 68, 65, 67, 3, 78, 78, 35, 99 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

