我已设置了一个函数,以我想要的格式获取当前日期和时间:
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);}
}
我创建了一个Object
,其值为(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做这件事。
答案 0 :(得分:1)
可能会将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...
}
创建对象后,该函数将自行评估。
答案 1 :(得分:1)
您可以覆盖数组上的推送...
var movements = [];
movements.push = function(transaction) {
transaction.date = date();
return Array.push(transaction);
};
答案 2 :(得分:0)
您目前设置的方式,只需将"date"
替换为date()
的函数调用:
//transactions
var initialBalance = new Transaction(1000,date(),"cash");
var addIn = new Transaction(500,date(),"cash");
var addOut = new Transaction(-300,date(),"card");
但是,正如其他人所建议的那样,可能有更好的方法来做你想要做的事情。