var a, b, c = {}

一世执手 提交于 2019-12-13 18:17:55

问题


I thought the syntax:

var a, b, c = {};

would mean that the three variables are separate, not references to the same {}.

Is this because {} is an object and this is the standard behavior?

So if I do:

var a, b, c = 0;

the three would indeed be separate and not references?

Thanks, Wesley


回答1:


They shouldn't be the same, no. Only c will be assigned the value.

a and b would just be declared, but not initialized to anything (they'd be undefined). c would, as the only one of them, be initialized to {}

Perhaps it's clearer when written on several lines:

var a,      // no assignment
    b,      // no assignment
    c = {}; // assign {} to c



回答2:


var a, b, c = {};

This will declare 3 variables (a, b, c) but define only 1 variable (c).

var a, b, c = 0;

This will declare 3 variables (a, b, c) but define only 1 variable (c).




回答3:


In the examples you only define the last element

a and b are undefined




回答4:


var a, b, c = {}; only defines the last var namely c. it's similar to the syntax var a = {}, b = [], c = 0;

it's just short hand for declaring multiple vars.




回答5:


Using coma to separate variables enables to define multiple variables in the same scope more compactly. In your sample, though, only c = {} and a and b would be undefined. You could use similar construct to assign something like

var a = {first: 'foo'}, 
    b = {second: 'bar'}, 
    c = {third: 'foobar'};

which would be equal to

var a = {first: 'foo'}, b = {second: 'bar'}, c = {third: 'foobar'};

and also to

var a = {first: 'foo'};
var b = {second: 'bar'};
var c = {third: 'foobar'};

And each one would only reference to their respective object. Using comas is basically just a visual aspect.




回答6:


Yes, the three would be separate.

The comma operator evaluates the left operand, then evaluates the right operand, then returns the value of the right operand.

This makes for a nice way to declare a bunch of variables in a row if you just rely on the evaluation of the operands and don't do anything with the returned value.

var i = 0, j = 1, k = 2; is basically equivalent to var i = 0; var j = 1; var k = 2

Another use for this is to squeeze multiple operations onto one line without using ;, like in a for loop with multiple loop variables:

for(var x=0,y=5; x < y; x++,y--)

Notice how both x++ and y-- can be performed on the same line.



来源:https://stackoverflow.com/questions/6941837/var-a-b-c

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