为什么循环中的javascript新对象返回最后创建的而不是数组中每个JSON的一个?

时间:2015-02-14 00:56:19

标签: javascript arrays json object javascript-objects

我正在尝试为包含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;
};

不明白为什么...... 谢谢你们:))

2 个答案:

答案 0 :(得分:0)

这很快就会成为一个重复的问题。关键问题是变量&#34; clock&#34;在所有间隔计时器处理程序之间,代码顶部是共享。 JavaScript范围始终处于功能级别。解决方法是使用另一个函数来构建间隔计时器处理程序。

答案 1 :(得分:0)

是..这是因为你在循环中创建'clock'var,所以它每次都重置,当循环结束时,'clock'等于它设置的最后一个值。在您的设置间隔函数中,它引用全局时钟var,因此它的每个版本将具有相同(最后)的值。

当您创建类似setInterval中的匿名函数时,它将不会在for循环的上下文中运行,它会在全局范围内运行,因此变量混乱。

你需要引用对象的clock属性,而不是函数本地的时钟变量。

我可能不会很好地解释这一点,但谷歌“javascript匿名函数”或“var that = this”因为这是解决此类问题的最常见方法。

相关问题