1

我已经设置了一个函数来以我想要的格式获取当前日期和时间:

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 来做这件事。

4

3 回答 3

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...
}

创建对象后,该函数将自行评估。

于 2013-10-31T15:59:04.227 回答
1

你可以覆盖你的阵列上的推送......

var movements = [];
movements.push = function(transaction) {
    transaction.date = date();
    return Array.push(transaction);
};
于 2013-10-31T16:00:51.207 回答
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");

但是,正如其他人所建议的那样,可能有更好的方法来做你想做的事情。

于 2013-10-31T16:02:03.107 回答