在JavaScript中循环两个数据对象并组合以产生所需的结果

时间:2016-06-06 15:50:28

标签: javascript arrays loops dictionary

我有一个数组和一个字典如下:




  this.rank = {
 1:“Ace”,
 2:“两个”,
 3:“三”,
 4:“四”,
 5:“五”,
 6:“六”,
 7:“七”,
 8:“八”,
 9:“九”,
 10:“十”,
 11:“杰克”,
 12:“女王”,
 13:“King”
};
 this.suit = ['C','D','H','S']
  




我怎样才能循环这些给了一副纸牌?





我目前有这个但是对如何添加西装感到困惑?


&# xA;
  this.cards = []

 for(var.ink中的var键){
 if(this.rank.hasOwnProperty(key)){
 this.cards.push(键)
 }
  




或者,是否有更好/更简单的方法?




2 个答案:

答案 0 :(得分:1)

这是一个可以使用 map 的解决方案。您没有指定要最终使用的数据结构,但可以从此处轻松修改。

cards.map(function(currVal){
  suit.map(function(secVal){
    console.log(currVal + ' ' + secVal);
  })
})

答案 1 :(得分:0)

您需要遍历this.suits或对4个索引进行硬编码。



this.rank = {
  1: "Ace",
  2: "Two",
  3: "Three",
  4: "Four",
  5: "Five",
  6: "Six",
  7: "Seven",
  8: "Eight",
  9: "Nine",
  10: "Ten",
  11: "Jack",
  12: "Queen",
  13: "King"
};

this.suit = ['C', 'D', 'H', 'S']

this.cards = []

for (var key in this.rank) {
  if (this.rank.hasOwnProperty(key)) {
    // you could loop through this.suit but for only 4 iterations it's probably faster just to hard code
    this.cards.push(this.rank[key] + this.suit[0]);
    this.cards.push(this.rank[key] + this.suit[1]);
    this.cards.push(this.rank[key] + this.suit[2]);
    this.cards.push(this.rank[key] + this.suit[3]);
  }
}

console.log(this.cards);