我有一个这样的数组:
["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"]
如何将其转换为类似的内容?
[[Date.UTC(2016,09,27),256100.83],[Date.UTC(2016,09,25),261091.57],[Date.UTC(2016,09,23),261391.58]]
我在AngularJS中尝试这个。
答案 0 :(得分:1)
你去。
它并不漂亮,但它有效,并且它不会使用eval
。
var a = ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"];
var result = a.map(function(element){
var row = JSON.parse(element.replace('Date.UTC(', '').replace(')', '').replace(/,0/g, ','));
return [new Date(row[0], row[1], row[2]), row[3]];
});
console.log(result);

返回数组,日期为JS Date
个对象。
答案 1 :(得分:0)
试试这个
const inputs = [
"[Date.UTC(2016,09,30),250500.00]",
"[Date.UTC(2016,09,29),255100.83]",
"[Date.UTC(2016,09,28),255600.82]"
]
const result = inputs.map(item => {
const trimItem = item
.replace('[Date.UTC(', '')
.replace(']', '')
.replace(')', '')
const trimItems = trimItem.split(',')
const YYYY = trimItems[0]
const MM = trimItems[1]
const DD = trimItems[2]
const result = [
Date.UTC(YYYY, MM, DD),
Number(trimItems[3])
]
return result
})
console.log(result)
答案 2 :(得分:0)
这是使用一些正则表达式的类似解决方案:)我想知道月份是以零还是一个作为索引开始! Javascript日期需要零月索引。
console.log(["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"].map(function(i){
var afloat;
var date = /Date\.UTC\((\d{4}),(\d{2}),(\d{2})\)/.exec(i);
date = new Date(Date.UTC(+date[1], +date[2] - 1, +date[3]));
afloat = +i.split('),')[1].split(']')[0];
return [date, afloat];
}))
答案 3 :(得分:0)
答案 4 :(得分:-1)
在georg的eval answer和Cerbrus的replace answer之间,有一个中间地带 eval
,但不使用{ {1}}:eval
new Function
这显然不安全,但它很短,并且没有var from = ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"];
var to = from.map( e => new Function( 'return'+e )() ) // To array
.map( ([a,b]) => [new Date(a), b] ); // date to Date
console.log( to );
经常带来的其他惩罚。