在条件表达式中声明变量(三元运算符) [英] declaring a variable within conditional expressions (ternary operator)

查看:90
本文介绍了在条件表达式中声明变量(三元运算符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在条件表达式中声明变量?

Is it possible to declare the variable within a conditional expression?

例如:下面的代码返回语法错误(因为我已经在条件表达式中声明了变量x?).

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 
 );
 }

显然可以通过在语句外添加 var x; 来解决此问题,但是是否可以在此处声明变量?

obviously this can be fixed by simply adding var x; outside the statement, but is it possible for variables to be declared here?

推荐答案

是否可以在条件表达式中声明变量?

Is it possible to declare the variable within a conditional expression?

不. var 是一个声明,和条件表达式的操作数是表达式.语言语法不允许这样做.幸运的是.

No. var is a statement, and the operands to a conditional expression are expressions. The language grammar doesn't allow it. Thankfully.

这篇关于在条件表达式中声明变量(三元运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆