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