列出两个不同数组的内容 - 例如一副卡片" rank" "西装"

时间:2016-10-14 14:51:05

标签: javascript arrays

我试图在javaScript中制作标准的牌组。我使用了两个阵列 - 一个用于排名,另一个用于套装。我想运行一个简单的程序来获取这些数组的内容并列出它们 - 所以我得到了俱乐部的王牌,俱乐部的两个,俱乐部的三个......&# 34;等

到目前为止,我得到的只是一个排名列表,例如" Ace,Two,Three ......"接下来是一套西装"俱乐部,钻石,红心......"

这是我的代码

<a href='www.example.com/blog'>

任何人都可以帮助我解决我出错的地方吗?

2 个答案:

答案 0 :(得分:2)

您可能希望suitedList看起来像这样:

output = document.getElementById("card");
var x = ["King ", "Queen ", "Jack ", "10 ", "9 ", "8 ", "7 ", "6 ", "5 ", "4 ", "3 ", "2 ","Ace "];
var y = ["Clubs ", "Diamonds ", "Hearts ", "Spades "];

function suitedList(){
  var list = "";
  for (j=0; j < y.length; j++){
    for (i=0; i < x.length; i++){
      list += x[i] + "of " + y[j] + "<br />";
    }
  }
  return list;
}

output.innerHTML = suitedList()
<div id="card"></div>  

当然,积累可以通过其他几种方式完成,但关键是 - 您在第一次迭代(suitedList)中从King of Clubs返回并覆盖整个innerHTML有这个值。

你有output.innerHTML = suitedList(),而不是output.innerHTML += suitedList(),它会将列表附加到块的当前值 - 如果你只想列出卡片就可以了,但如果你也想要列出,则不行早期的名单出现。

答案 1 :(得分:2)

您需要在从函数返回字符串之前连接它们。有点像:

LD_LIBRARY_PATH
var output = document.getElementById("card");
var x = ["King ", "Queen ", "Jack ", "10 ", "9 ", "8 ", "7 ", "6 ", "5 ", "4 ", "3 ", "2 ", "Ace "];
var y = ["Clubs ", "Diamonds ", "Hearts ", "Spades "];

//cycle through card ranks
for (i = 0; i < x.length; i++) {
  output.innerHTML += x[i];
}

output.innerHTML += '<br/>';

//cycle through card suits
for (j = 0; j < y.length; j++) {
  output.innerHTML += x[i];
}

function suitedList() {
  // will hold all the concatenated values
  var outString = '';

  for (j = 0; j < y.length; j++) {
    //console.log(outString);

    for (i = 0; i < x.length; i++) {
      // append suit/card to variable
      outString += x[i] + 'of ' + y[j];
      // adding a new line for easier reading (remove if unwanted)
      outString += '<br/>';
    }
  }
  
  // return concatenated string with all values
  return outString;
}

// override existing content of 'output'
output.innerHTML = suitedList();