【问题标题】:Loop over two data objects in JavaScript and combine to produce desired result [duplicate]在 JavaScript 中循环两个数据对象并组合以产生所需的结果 [重复]
【发布时间】:2016-06-06 15:50:27
【问题描述】:

我在下面有一个数组和一个字典:

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)){
      this.cards.push(key)
    }

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

【问题讨论】:

标签: javascript arrays loops dictionary


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您需要遍历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);

    【讨论】:

    • 干杯,这对我来说看起来不错!
    猜你喜欢
    • 2019-12-22
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多