array [x] .foo.push(e)将e添加到整个数组中

时间:2014-05-01 15:08:04

标签: javascript arrays

我有一个this.events数组,用于存储一周中每一天的多个事件。 这就是它的初始化方式

this.events = new Array(7);
for(var i = 0; i < this.events.length; i++) {
    this.events[i] = { content: [] };
}

我写了这个函数来添加事件,但它们被添加到this.events的所有元素而不是相应的日子

this.addEvent = function(day, e) {
    this.events[day].content.push(e);
    return e;
};

我做错了什么?

编辑:从此方法调用addEvent

this.load = function() {
    var data = {
        from: Math.floor(this.week[0].valueOf() / 1000),
        to: Math.floor(this.week[6].valueOf() / 1000)
    };
    var request = $.ajax({
        url: this.loadPath,
        data: data,
        type: 'POST',
        context: this
    });
    var deferred = $.Deferred();

    request.done(function(response) {
        var context = this;
        response = JSON.parse(response);

        response.forEach(function(event) {
            event.date = new Date(event.date);
            var thisEvent = {
                id: event.id,
                time: event.date.format('HH:MM'),
                title: event.title,
                description: event.description,
                color: event.color,
                link: event.link
            };

            context.addEvent(event.date.getRealDay(), thisEvent);
        });

        deferred.resolveWith(this);
    });
    request.fail(deferred.reject);

    return deferred.promise();
};

0 个答案:

没有答案