开发者

How can I evaluate an expression in a string?

开发者 https://www.devze.com 2023-02-08 07:11 出处:网络
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

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 s开发者_高级运维cript 3?

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

Regards Aparna


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.


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


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.


var myparams.id=0;

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

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

精彩评论

暂无评论...
验证码 换一张
取 消