I would like to know if there is a way to declare a local variable inside a sequence expression in Javascript. I want to declare the variable as a part of the sequence expression and not as a separate statement.
For example, I want to do something like this:
temp = "1", var a, ++i;
Thanks for the help guys!
Edit - I am trying to instrument Javascript (to find out potential DOM-based XSS)and the above code is just a snippet of the actual program. For example, I found a way to convert if statements to expressions using the ternary operator like:
if (a === 2) {a = 1} else {a = 3}
... is converted to a === 2 ? a = 1: a = 3;
? I wanted to know if var a = 2
can also be converted to an expression so that it can be added to a sequence expression.
As to why I am doing all this - I am replacing assignment statements in a JS program with a set of statements of my own. If I add in multiple statements in place of one single statement, it messes with the rest of the code. Therefore I am using a sequence expression to get around this.
For example, in a for loop like:
for (var i = 0; i < 2; i++) {}
I cant replace i = 0
with a bunch of semicolon separated statements. Thus I am trying to add in multiple statements with a sequence operator
Indeed you must begin with the var
keyword followed by declarations and a semi-column. Then you can start your sequence.
If you really don't like it or do not want to use a semi-column (for whatever reason) you can try to make anonymous functions and use arguments as local variables :
(function(temp, a, i){ i=a, i++ })("1", 1)
So in a for loop you can do something like :
for (var i=function(){ /* any statement you want */; return 0 }(); i<10; i++) { /* ... */ }
Hope that helps.
Apperently you want the statement var a = this.b
to be changed into something like this:
var a = this.b;
var lhs = a;
var rhs = this.b;
if(rhs == 1){
};
lhs = rhs;
To achieve this, you can write a separate function:
function xy(){
var a = this.b;
var lhs = a;
var rhs = this.b;
if(rhs == 1){
};
lhs = rhs;
return a;
}
To make this work inside of a for-loop, in a single line, you can transform it into this:
for (var lhs, rhs, a = (function(){var a = this.b; lhs = a; rhs = this.b; if(rhs == 1){} lhs = rhs; return a;}).apply(this, []); a < 10; a++)
That should basically do it. The apply
method guarantees that this
inside the function is the same as this
outside the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With