如何用JavaScript拆分数组中每个值的最后n个数字?
我们有一系列这样的文字-
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
我们需要编写一个接受此数组和数字n的JavaScript函数,如果对应的元素包含大于或等于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 ]
热门推荐
10 小学毕业父母简短祝福语
11 幼儿生日祝福语模板简短
12 新娘妈妈的祝福语简短
13 邻居聚会祝福语大全简短
14 十条祝福语简短
15 给同学祝福语的简短
16 过年祝福语简短祝妈妈
17 祝女儿简短祝福语大全
18 恩师诗词祝福语简短大全