so I’m trying to create a basic calculator. The add() method is supposed to take in the array (numsArray), remove the part of the array being added together, and replace it with the result (addedNum). addPoint is the + sign, so therefor it should start from numsArray[addPoint – 1] and delete 3 elements. The expected output should be 300,+,200,+,105. However, the output is 300,+,200,+,100,+5,105.
The add() method:
function add(addPoint, numsArray) { addedNum = parseInt(numsArray[addPoint - 1]) + parseInt(numsArray[addPoint + 1]); numsArray.splice(numsArray[addPoint - 1], 3, addedNum.toString()); return numsArray; }
The code:
var equation = "300 + 200 + 100 + 5".split(" "); console.log(equation.toString()); equation = add(5, equation); console.log(equation.toString());
I tried fiddling with the values, but splice() would only add the number to the front or the end of the array. Am I missing something? I’m new to js so the answer is probably very simple. Thanks in advance!