在JavaScript中拆分数组中每个值的最后n个数字
我们有一系列这样的文字-
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
我们需要编写一个接受此数组和数字n的JavaScript函数,如果对应的元素包含大于或等于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 ]
热门推荐
5 天仙配简短祝福语
10 学生国庆简短的祝福语
11 伴娘祝福语简短朋友的话
12 生日祝福语已婚朋友简短
13 姐妹订婚刺绣祝福语简短
14 给表妹生日祝福语简短
15 订婚典礼文案祝福语简短
16 毕业女孩祝福语简短独特
17 晚辈给长辈祝福语简短
18 生日贺卡祝福语英文简短