There was a problem writing a calculator.

for (var i = 0; i < calcBtn.length; i++){ calcBtn[i] = calcBtn.innerHTML; calcBtn[i].onclick = function btnClick() { +this; console.log(typeof this); calcInput.value += this.innerHTML; } } 

It is necessary to convert the object obtained from the array at the clique into a variable of the Number type in order to perform the mathematical operation in the future.

typeof this displays the object, but + this does not convert, I can not understand why? Help please, who knows?

  • What about +this.innerHTML ? - diraria
  • one
    calcBtn[i] = calcBtn.innerHTML; - what does that do? Remove this line. - Igor
  • for a simple calculator, you need the eval () method; with him it will be easier for you not to bother - xlabuchik
  • one
    + this does not convert - converts, you just do not save the result anywhere. - Grundy
  • show what you have in the calcBtn array - Grundy

1 answer 1

 var calcInput = document.getElementById("calcinput"); var calcBtn = document.querySelectorAll(".calc-btn"); for (var i = 0; i < calcBtn.length; i++){ calcBtn[i].onclick = function() { var buttonValue = +this.innerText; console.log(typeof buttonValue); console.log(buttonValue); calcInput.value += this.innerHTML; }; } 
 .calc-btn { display:inline-block; width:30px; height:30px; line-height: 30px; border:1px solid black; text-align:center; } 
 <div class="calc-btn">1</div> <div class="calc-btn">2</div> <div class="calc-btn">3</div> <div class="calc-btn">4</div> <div class="calc-btn">+</div> <br/> <br/> <input id="calcinput"/> 

  • Thank you very much, now I understand everything - Vladimir