连续循环遍历数组onClick并渲染每个元素

时间:2018-08-13 17:07:04

标签: javascript arrays reactjs object

我想遍历数组onClick并按数组长度一一呈现元素,当我到达数组末尾时要从头开始。例如,我有以下两个数组,我想循环遍历第一个数组,其长度与第二个数组的长度相同,但是每次第一个数组从结尾处开始时都从头开始:

const a = [a, b, c, d, e] and const b = [a, b, c, d, e, f, g, h]

changePlayers = () => {
  index++; // if this is the last item then go to first item
  index = index % a.length
}

我试图一次从第一个数组a[0]

中渲染每个元素。

这是我尝试制作的真相或冒险游戏。

4 个答案:

答案 0 :(得分:0)

请尝试以下操作:

 var numbers = [4, 9, 16, 25];
 var number1 = [3, 8, 15];
 var x = "";
 numbers.forEach(function(val){
   number1.forEach(function(val2){
      x += val2+" - "+val+ "<br>";
     });
  });

答案 1 :(得分:0)

您可以执行一次循环。运行您的循环并迭代第二个数组的长度。在循环外有一个变量(我将其命名为indexTracker),该变量将跟踪第一个数组的索引。然后在循环的if语句中,如果第一个数组的索引超出范围,则重置indexTracker

const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

// This will track the indices of the first array
// We'll reset this when we go out of bound
let indexTracker = 0;

// For the length of the second array
for(var i = 0; i < arr2.length; i++) {

  // If index does *not* exist for arr1
  if(!arr1[indexTracker]) {
    // reset the index tracker
    indexTracker = 0;
  }

  // Do whatever you want with arr1 values here.
  // You can return / render them, etc. I'm just console logging.
  console.log(arr1[indexTracker]);

  // Note: You can still use variable i to access values in arr2. I.e.:
  // console.log(arr2[i]);

  // Increment the indexTracker
  indexTracker++;
}

答案 2 :(得分:0)

这是我在W3school尝试时得到的答复。

HTML:            

 </head>
 <body>

  <button onclick="myfunction()">Click Me</button>
  <div id='demo'></div>
  <script>
       function myfunction(){

       var numbers = [4, 9, 16, 25];
       var number1 = [3, 8, 15];
        var x = "";
        numbers.forEach(function(val){
        number1.forEach(function(val2){
               x += val2+" - "+val+ "<br>";
            });
         });
         document.getElementById('demo').innerHTML = x;

        }
    </script>

    </body>
   </html>

输出


3 - 4
8 - 4
15 - 4
3 - 9
8 - 9
15 - 9
3 - 16
8 - 16
15 - 16
3 - 25
8 - 25
15 - 25

答案 3 :(得分:0)

以下是问题的答案

playerTurn = () => {
      let index = this.state.currentPlayer;
      index = index + 1;

      if (this.players[index]) {
        this.setState({ currentPlayer: index });
      } else {
        this.setState({ currentPlayer: 0 });
      }
};