3

我正在尝试将 2 个变量声明为相同的值( false )。

我倾向于在所有地方都这样做(比如,几乎在我原型的每个对象中)

var $a= {border:false
,frame:false};

或交替

border=false;frame=false;

有没有更好的方法可以同时声明两者的价值?(例如代码高尔夫解决方案)

4

3 回答 3

3

如果在设置值时声明了两个变量,则可以。这有点古怪,但它有效:

var frame, 
    border = frame = false;

(我认为这将是你能得到的最短的)

好点吗?我不这么认为,而且你并没有真正节省多少。更具可读性的是

var frame = false, 
    border = false;

实际上,您可以做更多的组合,但如果不重复变量名或值,您就无法做到这一点。例如,您还可以这样做:

var frame = false, 
    border = frame;

Of course this only works for primitive values (i.e. booleans, (literal) numbers, (literal) strings). If you deal with objects (which includes arrays), then both variables would reference the same object. In this case you really have to initialize them separately:

var frame = {}, 
    border = {};

// DON'T DO THIS:
var frame, 
    border = frame = {};

Update, because I feel the need to explain why var border = frame = false; does not work:

var is not transitive here and this expression is actually evaluated from right to left. First, false is assigned to frame, which will be looked up in the scope chain and in the worst case will become global. Then the value of frame is assigned to the local variable border.

于 2011-06-22T19:58:39.117 回答
2

你可以这样做:

var border = frame = false;
于 2011-06-22T19:47:16.167 回答
1

Consider:

var border, frame;

border = frame = false;
于 2011-06-22T20:03:11.203 回答