4
I’m creating a javascript calculator for better learning and am having difficulty in remover todos os elementos do array
. Know when you click the button "AC
" calculator and it removes everything? That’s what I want to do.
My code in HTML:
<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 code in Javascript:
<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>
No stackoverflow even I found answers to remove like this:
while(clicks.length) {
clicks.pop();
}
That from what I understood, he’d run the array
by the size of it and as long as there was something in it, it would remove the last element until it had nothing.
However, when I test in the browser, I add some numbers, delete with AC
and then add other numbers, the array
starts with several commas. I noticed that the amount of the comma, is the amount of previously deleted elements.
The problem is that I wanted to erase with the AC, he started from scratch even without the commas.
Follow my test image in the browser:
NOTE: I’ve tried clicks.length = 0 too and it didn’t help.
Why not reset the array with
clicks = []
?– Sam
I tried to reset with clicks = [] and continued the same problem.
– Marcielli Oliveira