-2

It is necessary to rewrite all the values of the array into a new variable, but so that the addition operator and subtraction operator is not be like a string, that is, so that the code is executed and the result is 3

How can my problem solve?

Code:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
let a = "1 + 3 - 1";
let arr = a.split(" ");

arr.forEach(function(item, i, arr) {});

//code here


</script>
</body>
</html>
  • There is no simple way of doing it.... eval and new Fuction() are one way. Or plenty of libraries out there to solve math. – epascarello May 18 '21 at 12:27
  • You could [write your own simple expression parser](https://stackoverflow.com/a/64934466/) (scroll to the bottom for an example that supports addition). Althought you can probably just use an existing AST parser and work on that output to evaluate it. Or use a library to do it for you. Not sure *why* you want to evaluate strings and how you want to do this. – VLAZ May 18 '21 at 13:08

2 Answers2

1

You do not need any array or loop here, you can use eval():

<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
  </head>
  <body>
    <script>
      let a = "1 + 3 - 1";
      let res = eval(a);
      console.log(res);
    </script>
  </body>
</html>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

use if condition(for example: if(i == "+"){}) to sort out accordingly with the next number. This is My Idea.I am Beginner in Js. Please debug this Script For Example:

<script>
arr = ["5" , "+" , "1" , "-", "1"];
k=arr.length;
z=[];
evolve();
function evolve(){
 for(i=0; i < k ; i = i+2) {
    for(j=0;j>-1;j++){
         if(arr[i] == `${j}`){
                z.push(j);
                evovle();
}
}
}
}
y=z[0]
ind =1
for(i=1;i<k;i = i+2){
     if(arr[i] == "+"){
      y=y+z[ind];
     ind++
      }
     if(arr[i] == "-"){
      y=y-z[ind];
     ind++
      }
}
</script>
<h1>{{y}}</h1>
Praveen M
  • 11
  • 3