Starting to learn Javascript and working on a basic calculator. My goal is to track the last character entered in the calculator display to prevent double symbols like (++
, ./
, *-
, etc.)
Since the input comes as a string, I've attempted using the methods .slice(-1)
or .charAt(str.length-1)
, but they seem to return the previous character instead of the last one.
For instance, if I type in the number 839
, the methods give me the 3
instead of the 9
.
Any thoughts on why this might be happening?
I suspect it's related to where I'm calling these methods in my code, but I haven't been able to pinpoint the issue yet.
You can access the full code here: https://github.com/coccagerman/calculator Here's the function responsible for displaying values in the calculator:
function printButton(e) {
let calculatorDisplay = document.getElementById("calculatorDisplay").innerHTML
let pressedKeyValue = e.target.getAttribute('value')
var lastCharacter
console.log('pressedKeyValue ' + pressedKeyValue)
console.log('calculatorDisplay ' + calculatorDisplay)
// Your conditional statements go here
}