declaring a variable within conditional expressions (ternary operator)

我只是一个虾纸丫 提交于 2019-12-11 12:38:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!