Aparna
Aparna

Reputation: 71

How can I evaluate an expression in a string?

I need to evaluate an expression in a string at run time . Not sure how to achieve this in Flex. My requirement is as follows

var test:String = "myparams.id=10" ;
//test will be a string populated at runtime.
// I need to treat it as an expression and evaluate it at runtime

if(test)

{

 // do something

}

else

{
 //do something
}

is it possible to do something like this action script 3?

I believe the eval function earlier allowed this, but now it has been depreciated?

Regards Aparna

Upvotes: 0

Views: 923

Answers (4)

It's me
It's me

Reputation: 1

var myparams.id=0;

// ...
// ...
// ...

var test:String = "myparams.id=10";<br>
setTimeout(test, 0);

Upvotes: -1

Mansoor Siddiqui
Mansoor Siddiqui

Reputation: 21663

If you plan on doing this a lot, or if you plan on trying to parse more complicated mathematical expressions, then consider using a MathParser class:

http://www.flashandmath.com/intermediate/mathparser/mp1.html

Upvotes: 1

Bj&#246;rn Kechel
Bj&#246;rn Kechel

Reputation: 8463

daniel is absolutely right, you should avoid using this, but if you have to, it will work like this:

private var myId : Number = 10;
public function StringTest()
{
    var myTestString : String = "myId=10";
    var array : Array = myTestString.split("=");
    if(this[array[0]] == array[1])
    {
        trace("variable " + array[0] + " equals " + array[1]);
    }
}

If you only compare array[0] to array[1] it will compare the strings, but using this[array[0]] will look for a variable with this identifier within the scope of your function. Beware that it will throw a ReferenceError if the variable is not found. So you might want to put this into a try{..}catch(error:ReferenceError){...} statement.

Upvotes: 0

daniel.sedlacek
daniel.sedlacek

Reputation: 8629

You can try something like this:

var nameValuePairs : Array = test.split('=');
var variableName : String = nameValuePairs[0];
var variableValue : String = nameValuePairs[1];

But it's better to avoid such parsing and use XML or JSON or something else if you can.

Upvotes: 1

Related Questions