1

I am using the eval() function to create an calculator, and as you know eval returns a string (I am referring to this tutorial), for example 20+30. What I want now is to split this string so I will have an array of data like [20,30,50] where the 20 and 30 are the operands and 50 is the result in this case.

What I did so far is:

var input = document.getElementById('screen');
var result= '20+30'; // as an example
var firstOperand = result.split('+', 1); //this is taking the first operand

What I really want is as I mentioned to turn my input value that is string "20+30" to an array: myArr = [20,30,50].

Any help?

2 Answers 2

1

Use the power of maps and reduce!

result = '1+2+3+4+5+6+7+8+9';
a = result.split('+').map(function(x){ return parseInt(x) });
b = a;
b.push(a.reduce(function(p, c) { return p+c; }));
// b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 45]

Btw you shouldn't use eval(), look into the Shunting-yard algorithm instead. Code examples for the algorithm can be found here at SO and at Rosettacode.

Sign up to request clarification or add additional context in comments.

Comments

0

you can create the array passing to the split function only the separator.

var myArr = result.split('+');

now you need to add the result:

myArr.push("50");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.