I'm in the process of developing a calculator that can compute the values within a string. To achieve this, I've implemented a Function object, but upon execution of the code, I encounter an issue where I receive a result of 'undefined'. My assumption is that this problem stems from the global scope of the Function object, yet I'm unable to pinpoint the exact error within the function. While passing it a local variable could potentially resolve the issue, I'm facing challenges in figuring out how to implement this solution.
let attachEventListeners = function () {
screens = document.querySelectorAll("[class=screen]");
operationsButtons = document.querySelectorAll("[class^=operations_button]");
initializeAttributes();
addNumberButtonListeners();
addOperationsListeners();
addOtherButtons();
}
function addNumberButtonListeners() {
numberButtons = document.querySelectorAll("[id^=number]");
numberButtons.forEach(button => {
button.addEventListener("click", function () {
let buttonNumber = button.innerText;
screens.forEach(screen => {
screen.numberLast = true;
if (screen.isDefault) {
screen.innerText = buttonNumber;
screen.isDefault = false;
if (screen.id == "little_screen") {
screen.value = screen.innerText;
}
}
else {
screen.innerText += buttonNumber;
if (screen.id == "little_screen") {
screen.value = screen.innerText;
}
}
})
})
});
}
// Other functions...
attachEventListeners()
// Additional styling and HTML content...
While I understand that using eval() would provide a solution, I am striving to avoid its usage. I have incorporated a console.log statement that displays the value of the string required for calculation each time you attempt a computation by pressing the equals button.
EDIT: After making some modifications, I no longer encounter the 'undefined' output. However, my current challenge lies in only receiving the raw string without performing the actual calculation.
let calculate = function () {
screen = document.querySelector("[id=little_screen]");
screen.innerText = screen.innerText.slice(0, -1);
return screen.innerText;