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]
4
Answers
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
?This should work. If found multiple problems.
( )
instead of these[ ]
because it’s a functioni++;
in the else block is not neededSplicing the array and modifying the length of it while iterating over it at the same time can cause all sorts of different issues. I tried a different approach where I form numbers iteratively and push them to the result array once formed.
Use
array.splice(index, deleteCount, ...items)
to replace the items in array:(and use
i--
to repeat loop on the same index)(and use unary + to convert to number if you convert to string by adding a string, I guess)