【发布时间】:2015-02-14 00:56:18
【问题描述】:
我正在尝试为包含 JSON 对象的数组的所有位置创建一个新对象作为 JSON 的属性,但问题是当运行它时,它总是打印出最后一个也是最后一个在内部创建的对象为循环。 我想不通这个... 谁能解释我为什么会这样? 这是我的代码:
for(var i = 0; i < data.length; i++){
var clock = new Clock((datesService.parseToClock(data[i].endsAt) / 1000), data[i].id)
data[i].clock = clock
data[i].interval = setInterval(function(){
clock.decrement()
console.log('ID: ' +clock.getAuction() + ' | ' + clock.getDays()+' d '+ clock.getHours()+' h ' + clock.getMinutes() + ' m ' + clock.getSeconds())
}, 1000)
}
function Clock(tempo, auction){
this.auction = auction
this.tempo = tempo
this.seconds = this.tempo % 60
this.minutes = (this.tempo / 60) % 60
this.hours = ((this.tempo / 60) / 60) % 24
this.days = (((this.tempo / 60) / 60) / 24)
}
Clock.prototype.decrement = function(){
this.tempo --
this.seconds = Math.floor(this.tempo % 60)
this.minutes = Math.floor((this.tempo / 60) % 60)
this.hours = Math.floor(((this.tempo / 60) / 60) % 24)
this.days = Math.floor((((this.tempo / 60) / 60) / 24))
};
Clock.prototype.getAuction = function(){
return this.auction
};
Clock.prototype.getDays = function(){
return this.days
};
Clock.prototype.getHours = function(){
return this.hours
};
Clock.prototype.getMinutes = function(){
return this.minutes
};
Clock.prototype.getSeconds = function(){
return this.seconds;
};
只是不明白为什么... 谢谢大家:)
【问题讨论】:
-
感谢您提出这个问题,您帮助我学习了 JS!
标签: javascript arrays json object javascript-objects