Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript进行多次左手分配(Multiple left-hand assignment with JavaScript)

var var1 = 1,
    var2 = 1,
    var3 = 1;

This is equivalent to this:

(这相当于:)

var var1 = var2 = var3 = 1;

I'm fairly certain this is the order the variables are defined: var3, var2, var1, which would be equivalent to this:

(我很确定这是变量定义的顺序:var3,var2,var1,它等价于:)

var var3 = 1, var2 = var3, var1 = var2;

Is there any way to confirm this in JavaScript?

(有没有办法在JavaScript中确认这一点?)

Using some profiler possibly?

(可能使用一些分析器?)

  ask by David Calhoun translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually,

(其实,)

var var1 = 1, var2 = 1, var3 = 1;

is not equivalent to:

(等于:)

var var1 = var2 = var3 = 1;

The difference is in scoping:

(区别在于范围界定:)

 function good() { var var1 = 1, var2 = 1, var3 = 1; } function bad() { var var1 = var2 = var3 = 1; } good(); console.log(window.var2); // undefined bad(); console.log(window.var2); // 1. Aggh! 

Actually this shows that assignment are right associative.

(实际上这表明赋值是正确的关联。)

The bad example is equivalent to:

(bad例子相当于:)

var var1 = (window.var2 = (window.var3 = 1));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...