问题
Is it possible to declare the variable within a conditional expression?
for example: The code below return a syntax error (because I've declared the variable x within the conditional expression?).
var a = document.getElementById("userData");
var d = a.value;
function() {
(d.length>15)?(
alert("your input was too long")):(
var x = parseInt(d).toString(2),
a.value=x
);
}
obviously this can be fixed by simply adding var x;
outside the statement, but is it possible for variables to be declared here?
回答1:
Is it possible to declare the variable within a conditional expression?
No. var is a statement, and the operands to a conditional expression are expressions. The language grammar doesn't allow it. Thankfully.
回答2:
You can do this with an immediately-invoked function:
(d.length>15)?(
alert("your input was too long")):
(function(){
var x = parseInt(d).toString(2);
a.value=x;
}())
);
But note that the x
variable will not exist outside of the inner function. (I can't tell whether you want it to exist after the expression is evaluated or not.)
回答3:
No. But you can initialize it with undefined
and set it with condition.
function Test()
{
d = 25.6654;
var x = (d.toString().length > 15) ? parseInt(d).toString() : undefined;
alert(typeof x === "undefined");
}
Then you can work with if(typeof x == "undefined") //do something
来源:https://stackoverflow.com/questions/19071803/declaring-a-variable-within-conditional-expressions-ternary-operator