在javascript中设置1行中的多个变量是否有效? (var x = y ='value';) [英] Is setting multiple variables in 1 line valid in javascript? (var x=y='value';)

查看:578
本文介绍了在javascript中设置1行中的多个变量是否有效? (var x = y ='value';)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这在php中有效:

$x=$y='value';

这将在esscence中将$ x和$ y设置为'value'。

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

这在javascript中有效吗?

Is this valid in javascript?

var x=y='value';

我已经在Chrome控制台测试了它,它按预期工作,但只是想在开始之前仔细检查使用它。

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

推荐答案

只有当 var y 为之前已定义,否则 y 全球

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';



作业链接



另一个创建隐含全局变量的反模式是将赋值链接为
var声明的一部分。在下面的代码片段中, a 是本地的,但 b 变为全局,这可能不是你想要的
要做:

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;
   // ...
}

如果你想知道为什么那样发生了,这是因为从右到左的评估。首先,
表达式 b = 0 被评估,在这种情况下,b未被声明。返回值
此表达式为 0 ,并将其分配给使用 var a 。用
换句话说,就像你输入的一样:

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模式,作者:Stoyan Stefanov
(O'Reilly)。版权所有2010 Yahoo!,Inc.,9780596806750。

这篇关于在javascript中设置1行中的多个变量是否有效? (var x = y ='value';)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆