I have a problem manipulating an arrangement in Javascript that I could not solve or explain the behavior.
Initially I have 9 buttons inside a div numbered from 1 to 9. By clicking on the button 5 the numbers of the buttons around it must turn in the sense of the needles of the clock.
To do this I add an event (I can not use jQuery) by directly manipulating the DOM. I create an array and I add the 8 buttons in the respective order, clone the array, to the cloned array I remove the last element and add it to the beginning (so I simulate moving the elements in a clockwise direction), then I assign the value of the objects of the cloned array to the new array.
The inconvenience that occurs is that you are assigning the number 4 to all the values surrounding the number 5. To verify this, in the code I added two codes that, first, show me the permuted cloned array and the values are the appropriate, but in the second for cycle, when returning to show the values of the permuted array are exactly the same (the number 4) without altering the array.
What could be happening?
var button5 = document.getElementById("btn5");
button5.onclick = function() {
var arrButtons = [];
//Inicialmente el arreglo contendrá los objetos a
//los botones representados por 1,2,3,6,9,8,7,4
arrButtons.push(document.getElementById("btn1"));
arrButtons.push(document.getElementById("btn2"));
arrButtons.push(document.getElementById("btn3"));
arrButtons.push(document.getElementById("btn6"));
arrButtons.push(document.getElementById("btn9"));
arrButtons.push(document.getElementById("btn8"));
arrButtons.push(document.getElementById("btn7"));
arrButtons.push(document.getElementById("btn4"));
//Clono el arreglo inicial.
var newButtons = arrButtons.slice();
//Permutar en el sentido de las agujas del reloj.
newButtons.unshift(newButtons.pop());
//Muestra el arreglo permutado correctamente
//De 1,2,3,6,9,8,7,4 ahora es 4,1,2,3,6,9,8,7 en la primera iteración
for (var i = 0; i < arrButtons.length; i++) {
console.log(newButtons[i].innerHTML);
}
for (var i = 0; i < arrButtons.length; i++) {
//Pero ahora solo muestra 4 para cada valor de newButtons[i] en la primera iteración
console.log(newButtons[i].innerHTML)
arrButtons[i].innerHTML = newButtons[i].innerHTML;
}
}
#btns {
width: 75%
}
#btns .btn {
width: 30%;
height: 48px;
font-size: 24px;
}
<div id="btns">
<button id="btn1" class="btn">1</button>
<button id="btn2" class="btn">2</button>
<button id="btn3" class="btn">3</button>
<button id="btn4" class="btn">4</button>
<button id="btn5" class="btn">5</button>
<button id="btn6" class="btn">6</button>
<button id="btn7" class="btn">7</button>
<button id="btn8" class="btn">8</button>
<button id="btn9" class="btn">9</button>
</div>