2

I tried to write a computation mathematical expression and store each sign into an array.

For example, I want to convert the array:

let arr = ['10', '-', '(', '2', '+', '1', ')', '*', '3'];

To the following expression:

let result = 10 - (2 + 1) * 3;  // 1

Any suggestions on how to achieve this?

4
  • 1
    eval(arr.join(' ')) Commented Aug 28, 2018 at 13:39
  • Mate I corrected it. You haven't clicked new changed link. Commented Aug 28, 2018 at 13:42
  • You can create your own calculator as well. We did it in college to practice stacks (for arrays it's the use of push and pop). Pretty much you keep pushing numbers to one array and operators to the other array. When you find something that has higher precedence, you handle it in place. You do this until the arrays are empty. Commented Aug 28, 2018 at 16:42
  • Yes, that is what I practice currently :) Commented Aug 28, 2018 at 22:09

2 Answers 2

2

It will not validate your input but eval(arr.join("")) will do it.
eval takes a string and executes it as it were a js expression.

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

2 Comments

I forgot I can use eval() to achieve this goal. Thank you so much
No problem, but keep in mind that this will only work if the expression is valid. Also, consider reading this before using eval.
2

It work only with eval,

new Function is not working for this issue

const arr = ['10', '-', '(', '2', '+', '1', ')', '*', '3'];

eval(arr.join(' ')); // 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.