在 1 行中设置多个变量在 javascript 中有效吗?(var x=y='value';)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7581439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is setting multiple variables in 1 line valid in javascript? (var x=y='value';)
提问by anonymous-one
This is valid in php:
这在 php 中有效:
$x=$y='value';
This will in esscence set both $x and $y to 'value'.
这将本质上将 $x 和 $y 设置为“值”。
Is this valid in javascript?
这在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.
我已经在 chrome 控制台中对其进行了测试,它按预期工作,但只是想在开始使用它之前仔细检查一下。
回答by user278064
It only works if the var y
as been previously defined, otherwise y
will be global.
它仅适用于var y
先前定义的,否则y
将是全局的。
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:
另一个创建隐含全局变量的反模式是将赋值链作为 var 声明的一部分。在以下代码段中,a
是本地的,但b
变为全局的,这可能不是您想要做的:
// 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:
如果您想知道为什么会发生这种情况,那是因为从右到左计算。首先,对表达式b = 0
求值,在这种情况下不声明 b。此表达式的返回值是0
,并将其分配给用 声明的新局部变量var a
。换句话说,就好像您输入了:
var a = (b = 0);
If you've already declared the variables, chaining assignments is fine and doesn't create unexpected globals. Example:
如果您已经声明了变量,那么链接赋值就可以了,并且不会创建 意外的 globals。例子:
function foo() {
var a, b;
// ...
a = b = 0; // both local
}
“JavaScript Patterns, by Stoyan Stefanov (O'Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”
“JavaScript 模式,作者 Stoyan Stefanov (O'Reilly)。版权所有 2010 Yahoo!, Inc.,9780596806750。”
回答by Dykam
To prevent the y from becoming a global variable, use the following:
要防止 y 成为全局变量,请使用以下命令:
var x, y = x = 'value';
Apparently the declarations are simply evaluated from left to right.
显然,声明只是从左到右进行评估。
回答by Steven Lu
I'm pretty sure that the most readable form is the one that has not been brought up yet:
我很确定最易读的形式是尚未提出的形式:
let x = 0, y = 0
回答by tonycoupland
Yes, that is valid in Javascript.
是的,这在 Javascript 中有效。
However, after googling the problem, this Stack Overflow questionexplains some caveats, so use with caution.
但是,在谷歌搜索问题后,这个Stack Overflow 问题解释了一些警告,所以请谨慎使用。
回答by maguri
When vars have different values you can easily write:
当 var 具有不同的值时,您可以轻松编写:
var x = 0,
y = 1,
...
z = 2;