I'm writing a calculator app. Buttons in html add elements to an array. When the user hits =, it will iterate through the array and combine numbers that have no mathematical symbol between them. However, I have to remove an element each time 2 numbers are combined.
let equation = [1,2,3,"/",1,2,3];
combineNumbers();
function combineNumbers()//call to start finding solution by merging numbers
{
for(let i = 1; i < equation.length;i++)//iterates length of equation starting at 1
{
if(isFinite(equation[i-1]) && isFinite(equation[i]))//checks if equation[i] and the index before it are numbers
{
equation[i-1] = '' + equation[i-1] + equation[i];//combines equation[i] and the index before
equation.splice[i];//removes element at index i
}
else
{
i++;
}
}
console.log(equation);
}
I have tried iterating the length of the array backwards which broke it more. I've tried different versions of splice including
equation.splice[i]
equation.splice[i,1]
Current output with equation.splice[i] is [12,23,3,"/",12,23,3]. It should be [123,"/",123]
You are confusing
[ ](index/property access) and( )(function call). It should beequation.splice(i, 1).Also, please note that removing an item will shift the other indices, so you will then skip one item unless you manually decrement your counter with
i--or iterate backwards instead of forwards.Also, I'm not sure why you manually skip the next item in your
else, is that intentional? Perhaps there should not be anyelse?