Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Is setting multiple variables in 1 line valid in javascript? (var x=y='value';)

This is valid in php:

$x=$y='value';

This will in esscence set both $x and $y to 'value'.

Is this valid in javascript?

var x=y='value';

I have tested it in chrome console and it worked as expected, but just wanted to double check before starting to use it.

question from:https://stackoverflow.com/questions/7581439/is-setting-multiple-variables-in-1-line-valid-in-javascript-var-x-y-value

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

1 Reply

0 votes
by (71.8m points)

It only works if the var y as been previously defined, otherwise ywill be global.

In such case, you better do:

var x, y;
x = y = 'value';

Assignments Chaining

Another antipattern that creates implied globals is to chain assignments as part of a var declaration. In the following snippet, a is local but b becomes global, which is probably not what you meant to do:

// antipattern, do not use
function foo() {
   var a = b = 0;
   // ...
}

If you’re wondering why that happens, it’s because of the right-to-left evaluation. First, the expression b = 0 is evaluated and in this case b is not declared. The return value of this expression is 0, and it’s assigned to the new local variable declared with var a. In other words, it’s as if you’ve typed:

var a = (b = 0);

If you’ve already declared the variables, chaining assignments is fine and doesn’t create unexpected globals. Example:

function foo() {
   var a, b;
   // ...
   a = b = 0; // both local
}

“JavaScript Patterns, by Stoyan Stefanov (O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...