我们有一系列这样的文字-
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 ]