skip to Main Content

Is it possible to convert/wrap an array value into a if statement? For clarification, the statement I received from my code is always a string in an array, and I want to execute it in an if block. Right now, it does not do a comparison because it is a string. So how can I convert a string into a statement that will be compared?

let counter = 11;
let statement = ['counter > 10']; // array string received from other code (always a string)

if(statement[0]) {
    // should be true
}

Result expected to be true, where the if statement is dynamically executed.

EDIT: I found an answer by Using Function:

Execute JavaScript code stored as a string

3

Answers


  1. let counter = 11;
    let statement = ['counter > 10']; // (always a string)
    
    if (eval(statement[0])) {
        console.log("The statement is true");
    } else {
        console.log("The statement is false");
    }
    
    Login or Signup to reply.
  2. I think a better way to ask this question is "How to evaluate a string as if it were Javascript code. There is a way to do it in JavaScript using the eval method.

    let counter = 11;
    let statement = ['counter > 10']; // (always a string)
    
    if (eval(statement[0])) {
          // should be true
    }
    

    However, I would really not recommend using this. It’s a huge security risk. Please use it only if you know what you are doing.

    Referehce: https://www.w3schools.com/jsref/jsref_eval.asp

    Login or Signup to reply.
  3. You may be able to use the math parser for this, though I’m not sure. It’ll depend on what kind of things you get back in that string.

    // https://github.com/silentmatt/expr-eval/tree/master
    // there may be other ways to do this, this is simple though
    import Parser from 'expr-eval'; 
    
    const options = {x:3};   //see the documentation
    
    const parsedStatement = statement[0];
    const result = Parser.evaluate(parsedStatement, {options});
    console.debug('Expression Result: ', result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search