我已经设置了一个函数来以我想要的格式获取当前日期和时间:
function date(){
var d = new Date();
var minutes = d.getMinutes();
var month = d.getMonth() +1;
if(minutes<10){
return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + "0" + minutes);
}else{
return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + minutes);}
}
我创建了一个对象
,它接受值(amount,date,type)
。我如何设置它以便对象的每个新实例都由函数 date()
自动生成日期值,这样当它被推送到数组时 movements
添加时间戳?
这是我的代码:
var movements =[];
//transactions
var initialBalance = new Transaction(1000,"date","cash");
var addIn = new Transaction(500,"date","cash");
var addOut = new Transaction(-300,"date","card");
//add the transactions to the movements array
movements.unshift(initialBalance);
movements.push(addIn);
movements.push(addOut);
我想用纯 JS 来做这件事。
最佳答案
也许给对象添加date
函数
var Transaction = function(amount, type) {
this.date = (function() {
var d = new Date();
var minutes = d.getMinutes();
var month = d.getMonth() +1;
if (minutes<10) {
return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + "0" + minutes);
} else {
return (d.getDate() + "/" + month + "/" + d.getFullYear() + " " + d.getHours() + ":" + minutes);
}
})();
// now deal with amount and type...
}
创建对象后,该函数将自行评估。
关于javascript - 如何将当前日期动态添加到对象的新实例并将其推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19711188/