I'm creating a calculator in javascript for better learning and I'm having difficulty with remover todos os elementos do array
. Do you know when you click on the " AC
" button on the calculator and it removes everything? That's what I want to do.
My HTML code:
<div class="row" id="btnTop">
<div class="btn-group btn-group-lg">
<button type="button" class="btn btn-light" id="AC" onclick="clicado(this.id)">AC</button>
<button type="button" class="btn btn-light" id="/" onclick="clicado(this.id)">/</button>
<button type="button" class="btn btn-light" id="x" onclick="clicado(this.id)">x</button>
<button type="button" class="btn btn-light" id="<" onclick="clicado(this.id)"><</button>
</div>
</div> <!-- Fim btnTop -->
<div class="row" id="btn789">
<div class="btn-group btn-group-lg">
<button type="button" class="btn btn-light" id="7" onclick="clicado(this.id)">7</button>
<button type="button" class="btn btn-light" id="8" onclick="clicado(this.id)">8</button>
<button type="button" class="btn btn-light" id="9" onclick="clicado(this.id)">9</button>
<button type="button" class="btn btn-light" id="%" onclick="clicado(this.id)">%</button>
</div>
</div> <!-- Fim btn789 -->
My JavaScript code:
<script type="text/javascript">
var i = 0;
var clicks = Array();
function clicado(id) {
if (id != "AC" && id != "<") {
clicks[i] = id;
i++;
// document.getElementById("mostrarValores").innerHTML = id;
console.log("Array: "+clicks);
}
if (id == "<") {
clicks.pop();
console.log("Array Removido: "+clicks);
}
if (id == "AC") {
while(clicks.length) {
clicks.pop();
}
console.log("Array Zerado: "+clicks);
}
}
</script>
In the same stackoverflow I found answers to remove like this:
while(clicks.length) {
clicks.pop();
}
As far as I understood, it would run array
by its size and as long as it had something in it, it would remove the last element until it had nothing.
However, when I test in the browser, I add some numbers, I delete with AC
and then add other numbers, array
starts with multiple commas. I noticed that the number of the comma is the amount of elements deleted previously.
The problem is that I wanted to delete it with the AC, it started from scratch without the commas.
Follow the image of my test in the browser:
NOTE: I already tried clicks.length = 0 also and it did not work.