Javascript 如何拆分字符串数组中每个值的最后2位数字
我有一个数组:Javascript 如何拆分字符串数组中每个值的最后2位数字,javascript,arrays,split,Javascript,Arrays,Split,我有一个数组: last7day = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225] 我想把最后两位数分开。我在上一个7天尝试了类似slice命令的split-2,但没有成功 期望输出: 您可以使用负值作为第二个参数 var last7day=[20191219201912202019122120191222201912232019122420191225], 结果=最后7天。0,-2; c
last7day = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225]
我想把最后两位数分开。我在上一个7天尝试了类似slice命令的split-2,但没有成功
期望输出:
您可以使用负值作为第二个参数
var last7day=[20191219201912202019122120191222201912232019122420191225],
结果=最后7天。0,-2;
console.logresult 将数字更改为string,然后使用slice。然后,您可以使用parseInt将字符串值转换回数字,或者为拼接结果附加+号 var last7day=[20191219201912202019122120191222201912232019122420191225]; var res=last7day.mapitem=>item+item.toString.0,-2:; console.logres 您可以使用slice函数执行此操作。请尝试下面的代码
var last7day = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
const finalArray= last7day.map(day => day.slice(-2));
console.log(finalArray);
最后,这将是基于问题最后一次编辑的输出: 最近7天的施工时间=[,20191219,20191220,20191221,20191222,20191223,20191224,20191225]; 常量getLast2Digits=e=>{ //直接返回字符串 iftypeof e=='string'返回e; //转换为字符串,然后使用最后两个字符并重新转换为数字 否则返回parseIntStringe.substr-2; }
console.loglast7days.mapgetLast2Digits 您可以转换为字符串,然后使用子字符串方法: 例如: var last7day=[20191219201912202019122120191222201912232019122420191225] const result=last7day.mapd=>[d.toString.substring 0,4,, d、 toString.Substring 4、6、, d、 toString.Substring 6,8] console.logresult
使用substr方法获取最后2位数字 将元素转换为字符串 获取每个元素的最后两个字符 const last7day=[20191219201912202019122120191222201912232019122420191225] 常数结果=最后7天 .mapx=>{ 如果x的类型=='number'{ 常数y=x.toString; 返回y.substry.length-2 } 返回x } console.logresult您可以这样使用 让last7day=[20191219201912202019122120191222201912232019122420191225] 让newDays=last7day.mapi=>{ 返回i.toString.substr-2 }
console.lognewDays 您只需将除法的剩余部分乘以100:
last7day.map(x => x % 100)
如果数组中有要跳过的字符串,可以检查值是否为数字:
last7day.map(x => typeof(x) === 'number' ? x % 100 : "")
你真的不需要将数字转换成字符串再转换回来。你想要的输出是什么,你能包含你尝试过的实际代码吗?你是在尝试拆分元素还是数组本身?我需要这些值的最后2位作为数组,如last7day=[,19,20,21…]@KutayDeril看一看我下面的答案,然后它做了你想做的事我想他想把每个元素的最后一个数字分开,因此这不是问题的答案你没有把它们分开,你把它们去掉了…@EugeneSunic OP想去掉最后两个数字我用它作为var xAxis=last7day.mapday=>day.slice-2;成功了,谢谢你。
const result = last7day.map(d =>
[
d.toString().substring(0, 4),
d.toString().substring(4, 6),
d.toString().substring(6, 8)
])
const array = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
const numArray = array.map(v => {
if(typeof v === 'number') {
const num = v.toString();
const c = num.substring(num.length -2, num.length);
return parseInt(c);
}
return v
});
console.log(numArray)
last7day.map(x => x % 100)
last7day.map(x => typeof(x) === 'number' ? x % 100 : "")