如何使用 JavaScript 分割数组中每个值的最后 n 位数?
我们有一个这样的文字数组 −
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 ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP