如何显示js中递归函数的每一步?

时间:2018-09-21 06:03:40

标签: javascript html function ecmascript-6 ecmascript-5

我有一个递归函数。并且在HTML中有3个div,例如监视器(slot_a,slot_b,slot_c)。算法类似于河内塔。 因此,我想在每个显示器中查看每个插槽中发生了什么。为此,我使用innerHTML。但是我在每个插槽中只能得到相同的文本。 如何使它们与众不同?

const moveCranes = function(plate, slot_a, slot_b, slot_c) {
    moveCranes(plate - 1, slot_a, slot_c, slot_b);
    port_a.innerHTML = "Moving plate " + plate + " from " + slot_a + " to " + slot_c + "..." + "</br>";
    port_b.innerHTML = "Moving plate " + plate + " from " + slot_a + " to " + slot_c + "..." + "</br>";
    port_c.innerHTML = "Moving plate " + plate + " from " + slot_a + " to " + slot_c + "..." + "</br>";
    moveCranes(plate - 1, slot_b, slot_a, slot_c);
}
}
moveCranes(input.value,"slot_a","slot_b","slot_c");

1 个答案:

答案 0 :(得分:0)

尝试一下:

port_a = document.getElementById("port_a");
step = 1;
$row = $("<div class='row'>"+
          "<div class='col-xs-3 plate'><p>Plate</p></div>"+
          "<div class='col-xs-3 a'><p>A</p></div>"+
          "<div class='col-xs-3 b'><p>B</p></div>"+
          "<div class='col-xs-3 c'><p>C</p></div>"+
          +"</div>");
$container = $("#container");
const moveCranes = function(plate, slot_from, slot_to, slot_aux) {
	if(plate == 1){
        let $temp = $row.clone();
        $temp.find('.plate').append("<h1>"+plate+"</h1>");
        $temp.find('.'+slot_from).append("<h1>-</h1>");
        $temp.find('.'+slot_to).append("<h1>+</h1>");
        $container.append($temp);
        port_a.innerHTML += step++ + ". Moving plate " + plate + " from " + slot_from + " to " + slot_to + "..." + "</br>";
  }
  else{
        moveCranes(plate - 1, slot_from, slot_aux, slot_to);
        let $temp = $row.clone();
        $temp.find('.plate').append("<h1>"+plate+"</h1>");
        $temp.find('.'+slot_from).append("<h1>-</h1>");
        $temp.find('.'+slot_to).append("<h1>+</h1>");
        $container.append($temp);
        port_a.innerHTML += step++ + ". Moving plate " + plate + " from " + slot_from + " to " + slot_to + "..." + "</br>";
        moveCranes(plate - 1, slot_aux, slot_to, slot_from);
    }
}

moveCranes(3,"a","b","c");
.row{
  border: 1px solid black;
  margin-bottom: 10px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container" id="container">
  
</div>

<div id="port_a"></div>