繁体   English   中英

迭代关联数组的前x个元素

[英]Iterate first x elements of an associative array

具有12个元素的关联数组;

 this.rolls = {1:[], 2:[], 3:[], 4:[], 5:[],
                6:[], 7:[], 8:[], 9:[],10:[], 11:[], 12:[]};

最有效的方法是获取前10个元素的总和。 下面的代码当前汇总所有元素;

  var sum = 0;
  for (var k in this.rolls) {
    vals = this.rolls[k];
    for (var i=0; i<vals.length; i++) {
      sum += vals[i] || 0
    };
  };
  this.score = sum

前10个元素是:

 this.rolls = {1:[], 2:[], 3:[], 4:[], 5:[],
                    6:[], 7:[], 8:[], 9:[],10:[]};

这是完整的代码:

function Game() {
  this.score = 0;
  this.frameOver = false;
  this.rolls = {1:[], 2:[], 3:[], 4:[], 5:[],
                6:[], 7:[], 8:[], 9:[],10:[], 11:[], 12:[]};
  this.currentFrame = 1;
  // this.lastFrameStrike = false;
  // this.lastFrameSpare = false;
  // this.isStrike = false
};

Game.prototype.roll = function(pins) {
  this.strikeOrSpare(pins);
  this.bonusDistributor(pins);
  this.rolls[this.currentFrame].push(pins);
  this.scoreUpdater(pins);
  this.frameHandler(pins);
  this.nextFrameBonus(pins)
};

// --------------------------------------------------

Game.prototype.strikeOrSpare = function(pins) {
  if (pins === 10) {
    this.isStrike = true;
    this.frameOver = true
  }
  else if (this.rolls[this.currentFrame][0] + pins === 10) {
    this.isSpare = true;
    this.frameOver = true
  };
};

// --------------------------------------------------

Game.prototype.bonusDistributor = function(pins) {
  if(this.wasSpare) { this.addToLastSpare(pins) };
  if(this.wasStrike) { this.addToLast(pins) };
  if(this.wasStrike2 && this.currentFrame > 1) { this.addToLastAgain(pins) };
};

// --------------------------------------------------

Game.prototype.addToLast = function(pins) {
  this.rolls[this.currentFrame - 1][0] += pins
};

Game.prototype.addToLastAgain = function(pins) {
  this.rolls[this.currentFrame - 2][0] += pins
};

Game.prototype.addToLastSpare = function(pins) {
  this.rolls[this.currentFrame - 1][1] += pins;
  this.wasSpare = false
};

// --------------------------------------------------

Game.prototype.scoreUpdater = function(pins) {
  var sum = Object.keys(this.rolls).sort(function (a, b) {
      return (+a) - (+b);
  }).slice(0, 10).reduce(function (p, c) {
      return p + this.rolls[c].reduce(function (p, c) {
          return p + c;
      }, 0);
  }, 0);
};

Game.prototype.frameHandler = function(pins) {
  if (this.frameOver) {
    this.currentFrame++; this.frameOver = !this.frameOver
  } else {
  this.frameOver = !this.frameOver;
  };
};

Game.prototype.nextFrameBonus = function(pins) {
  if (this.isSpare) {
    this.wasSpare = true;
    this.isSpare = false
    if (this.wasStrike) {
      this.wasStrike = false;
      this.wasStrike2 = true
    }
  } else if (this.isStrike && this.wasStrike) {
    this.wasStrike2 = true
  } else if (this.isStrike) {
    this.isStrike = false;
    this.wasStrike = true
  } else if (this.wasStrike) {
    this.wasStrike = false;
    this.wasStrike2 = true
  } else if (this.wasStrike2) {
    this.wasStrike2 = false
  };
};

// --------------------------------------------------

您遇到的第一个问题是this.rolls是一个Object ,而不是Array ,因此不能保证 for (var k in this.rolls)枚举键顺序。 因此,要解决的第一个问题是获取前10个键,将其转换为数字,然后对其进行排序。 在这里,我使用所有本机ArrayObject方法:

var rolls = this.rolls;
var sum = Object
  // Get all keys
  .keys(rolls)
  // Convert string keys to integers
  .map(function (key) { return parseInt(key, 10); })
  // Sort in ascending order
  .sort()
  // Take the first 10
  .slice(0, 10)
  // Get the arrays for each key
  .map(function (key) { return rolls[key]; })
  // Merge all arrays into one array
  .reduce(function (allNumbers, array) { return allNumbers.concat(array); }, [])
  // Sum all numbers
  .reduce(function (sum, number) { return sum + (number || 0); }, 0);

对对象键进行排序和过滤,然后使用它们减少要求和的数组

var rolls = this.rolls;
var sum = Object.keys(rolls).sort(function (a, b) {
    return (+a) - (+b);
}).slice(0, 10).reduce(function (p, c) {
    return p + rolls[c].reduce(function (p, c) {
        return p + c;
    }, 0);
}, 0);

DEMO

编辑:您的示例中有一个错误。 您不能使用 forEach 滚动 声明它( var self = this;或者我的版本是var rolls = this.rolls;外)

我建议使用以下代码来计算总和:

var sum = 0;
var rolls = this.rolls;
Object.keys(rolls).forEach(function (key, i, array) {
    if (i < 10) {
        var item = rolls[key].slice();
        while (item.length) {
            sum += item ? Number(item.shift()) : 0 + item ? Number(item.pop()) : 0;
        }
    }
});
console.log(sum, this.rolls);
this.score = sum;

有完整的示例:

 function Game() { this.score = 0; this.frameOver = false; this.rolls = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [], 11: [], 12: []}; this.currentFrame = 1; // this.lastFrameStrike = false; // this.lastFrameSpare = false; // this.isStrike = false } Game.prototype.roll = function (pins) { this.strikeOrSpare(pins); this.bonusDistributor(pins); this.rolls[this.currentFrame].push(pins); this.scoreUpdater(pins); this.frameHandler(pins); this.nextFrameBonus(pins); }; // -------------------------------------------------- Game.prototype.strikeOrSpare = function (pins) { if (pins === 10) { this.isStrike = true; this.frameOver = true; } else if (this.rolls[this.currentFrame][0] + pins === 10) { this.isSpare = true; this.frameOver = true; } }; // -------------------------------------------------- Game.prototype.bonusDistributor = function (pins) { if (this.wasSpare) { this.addToLastSpare(pins); } if (this.wasStrike) { this.addToLast(pins); } if (this.wasStrike2 && this.currentFrame > 1) { this.addToLastAgain(pins); } }; // -------------------------------------------------- Game.prototype.addToLast = function (pins) { this.rolls[this.currentFrame - 1][0] += pins; }; Game.prototype.addToLastAgain = function (pins) { this.rolls[this.currentFrame - 2][0] += pins; }; Game.prototype.addToLastSpare = function (pins) { this.rolls[this.currentFrame - 1][1] += pins; this.wasSpare = false; }; // -------------------------------------------------- Game.prototype.scoreUpdater = function (pins) { var sum = 0; // var self = this; var rolls = this.rolls; Object.keys(rolls).forEach(function (key, i, array) { if (i < 10) { var item = rolls[key].slice(); while (item.length) { sum += item ? Number(item.shift()) : 0 + item ? Number(item.pop()) : 0; } } }); console.log(sum, this.rolls); this.score = sum; }; Game.prototype.frameHandler = function (pins) { if (this.frameOver) { this.currentFrame++; this.frameOver = !this.frameOver; } else { this.frameOver = !this.frameOver; } }; Game.prototype.nextFrameBonus = function (pins) { if (this.isSpare) { this.wasSpare = true; this.isSpare = false; if (this.wasStrike) { this.wasStrike = false; this.wasStrike2 = true; } } else if (this.isStrike && this.wasStrike) { this.wasStrike2 = true; } else if (this.isStrike) { this.isStrike = false; this.wasStrike = true; } else if (this.wasStrike) { this.wasStrike = false; this.wasStrike2 = true; } else if (this.wasStrike2) { this.wasStrike2 = false; } }; var game = new Game(); game.scoreUpdater(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM