在javascript中达到特定数字时如何间隔地从x ++变为x--?

时间:2018-11-10 18:36:18

标签: javascript

我正在构建一个小型javascript程序。

程序在Windows加载时运行。我设置一个间隔使函数启动。因此,我想知道当在for循环中到达一定数量的遍历(通过脚本开头定义的数组的每个元素)时,如何从x ++到i递增。 这是我的脚本:

// we create the patterns array
var pattern = [
  [1, 0, 1],
  [0, 1, 0],
  [1, 0, 1]
];

var stage = document.querySelector("#stage");

// here we assign the width of the cell divs and space margin between them
var WIDTH = 30;
var SPACE = 10;

// here we get the number of rows in an array
var ROWS = pattern.length;

// here we get the number of columns in an array
var COLUMNS = pattern[0].length;

var previousColorNum = 0;

setInterval(render, 2000);

function render() {
  for (var row = 0; row < ROWS; row++) {
    for (var column = 0; column < COLUMNS; column++) {
      // here we create a div element
      var cell = document.createElement("div");

      // here we set the attribute class with the name cell
      cell.setAttribute("class", "cell");

      // here we append this new div to stage div
      stage.appendChild(cell);

      // now we check if the element of the array is 1 we give it a background of black
      // if the element is 0 it is white
      if (pattern[row][column] === 1) {
        cell.style.backgroundColor = "black";
      } else if (pattern[row][column] === 2) {
        cell.style.backgroundColor = "red";
      } else if (pattern[row][column] === 3) {
        cell.style.backgroundColor = "green";
      }
      previousColorNum = pattern[row][column];
      //pattern[row][column] += 1;

      if (previousColorNum === 3) {
        pattern[row][column] -= 1;
      } else if (previousColorNum === 0) {
        pattern[row][column] += 1;
      }



      // now we make the arrangement of margins for each div cell
      // it is a mathematical formula
      cell.style.top = row * (WIDTH + SPACE) + "px";
      cell.style.left = column * (WIDTH + SPACE) + "px";


      console.log("previous " + previousColorNum);
      console.log("current " + pattern[row][column]);

    }
  }
}
.stage {
  position: relative;
}

.cell {
  position: absolute;
  width: 30px;
  height: 30px;
  border: 1px solid black;
  background-color: white;
}


/* smaller console */
.as-console-wrapper { max-height: 2.5em !important; }
<div id="stage"></div>

0 个答案:

没有答案