Javascript 如何在单个声明中将多个局部变量设置为相同的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35903822/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:21:40  来源:igfitidea点击:

How to set multiple local variables to the same value in a single declaration?

javascript

提问by vol7ron

Consider the following:

考虑以下:

(function(){
   var foo = bar = 1;
}());
  • foowill be a local variable to the function
  • barwill be a global variable to the window
  • foo将是函数的局部变量
  • bar将是窗口的全局变量

Due to their scoping, both variables will have a value of 1 inside the function, but barwill persist outside the function (in global scope).

由于它们的作用域,两个变量在函数内的值都为 1,但bar将在函数外(在全局范围内)保持不变。

I'm curious if there is a way to initialize variables using the assignment operator, without a loop or an object. I'm looking for a keyword or prefix that would make barlocally scoped. The idea is to be DRY and efficient.

我很好奇是否有一种方法可以使用赋值运算符来初始化变量,而无需循环或对象。我正在寻找一个关键字或前缀,可以使bar 成为本地范围。这个想法是干燥和高效的。



Edit: The example above is simple. One option, using 10 variables, might be to predeclare the variable to the local scope before initializing it:

编辑:上面的例子很简单。使用 10 个变量的一种选择可能是在初始化之前将变量预先声明到本地范围:

var foo, bar, baz, foobar, foobaz, bazfoo, barbaz,
    bazbar = foo = bar = baz = foobar = foobaz = barbaz = true;

However, doing so is both repetitive and harder to read. A person could use an array or object, but that is a little less clear and more cluttered.

但是,这样做既重复又难以阅读。一个人可以使用数组或对象,但这有点不太清楚,而且比较混乱。

The background was that another developer was doing var foo = bar = trueinside a function, which I pointed out is only setting one local variable. They were not aware of that and wanted to change and asked if it's possible to inline and set multiple local variables, without typing each one multiple times (and not refactor code w/ array or object).

背景是另一位开发人员var foo = bar = true在一个函数中做,我指出它只是设置一个局部变量。他们没有意识到这一点,想要改变并询问是否可以内联和设置多个局部变量,而无需多次键入每个变量(并且不使用数组或对象重构代码)。

Upon originally asking this question, I was exposed to ES6, but had yet to fully read the docs. My thinking was that ES6 has some nice features (e.g., rest, destructuring assignment) and so perhaps it also provided a way to massively initialize a large block of variables to the same scope and value.

最初问这个问题时,我接触了 ES6,但还没有完全阅读文档。我的想法是 ES6 有一些很好的特性(例如,休息、解构赋值),所以也许它也提供了一种将一大块变量大规模初始化为相同范围和值的方法。

采纳答案by Oriol

You can't (or shouldn't) assign a value to an undeclared variable.

您不能(或不应该)为未声明的变量赋值。

Then, when you want to declare multiple variable with the same value, you can

然后,当你想声明多个具有相同值的变量时,你可以

  • Assign the same value to each variable:

    var var1 = value,
        var2 = value,
        /* ... */
        varN = value;
    

    In case valueis an expensive expression, you can use var1instead of repeating valueto avoid recalculating it each time, e.g.

    var foo = 1, bar = foo;
    
  • Declare all variables first, and then assign the values to all of them:

    var var1, var2, /* ..., */ varN;
    var1 = var2 = /* ... = */ varN = value;
    

    You can do it in a single statement and avoid repeating the last variable, e.g.

    var foo, bar = foo = 1;
    
  • If you really want to avoid repeating the variables and the values, you could try a destructuring assignmentwith [].fill:

    var [var1, /*...*/ varN] = new Array(n).fill(value);
    

    But I don't recommend it because it will create an useless array.

  • 为每个变量分配相同的值:

    var var1 = value,
        var2 = value,
        /* ... */
        varN = value;
    

    如果value是一个昂贵的表达式,您可以使用var1而不是重复value以避免每次都重新计算它,例如

    var foo = 1, bar = foo;
    
  • 首先声明所有变量,然后为所有变量赋值:

    var var1, var2, /* ..., */ varN;
    var1 = var2 = /* ... = */ varN = value;
    

    您可以在单个语句中完成并避免重复最后一个变量,例如

    var foo, bar = foo = 1;
    
  • 如果你真的想避免重复变量的值,你可以尝试解构赋值[].fill

    var [var1, /*...*/ varN] = new Array(n).fill(value);
    

    但我不推荐它,因为它会创建一个无用的数组。

回答by Facebook Staff are Complicit

It's not very nice, but here's an interesting option that's sort-of DRY:

这不是很好,但这里有一个有趣的选项,有点 DRY:

(function(){
  with ({_: 1}) var x = _, y = _;
}());

The withstatement creates a de-facto temporary _variable, which we apply only to our varstatement to ensure there are no other side effects. This does repeat _, but avoids repeating anything meaningful. However, this is a terrible choice because (a) it kills the optimizer by using with, (b) it's not supported in strict mode due to using with, and (c) it relies on var's scope semantics, which we're all trying to get away from by using letand constfrom now on.

with语句创建了一个事实上的临时_变量,我们仅将其应用于我们的var语句以确保没有其他副作用。这确实重复_,但避免重复任何有意义的事情。然而,这是一个糟糕的选择,因为 (a) 它通过使用 来杀死优化器with,(b) 由于使用with,它在严格模式下不受支持,以及 (c) 它依赖于var的范围语义,我们都在努力从使用脱身let,并const从现在开始。

I suppose we could use this more coherent ES6 equivalent.

我想我们可以使用这个更连贯的 ES6 等价物。

(function(){
  { let _ = 1; var x = _, y = _; }
}());

However, I feel even more wrong to be taking advantage of varand let's different semantics in the same line.

但是,我觉得在同一行中利用varlet的不同语义更加错误。

Let's forget we ever had this train of thought.

让我们忘记我们曾经有过这样的想法。



If you want to declare two variables and initialize them using a single expression inside of a single statement, the only reasonable syntactic option the following. There is no option that avoids repeating the variable name without involving an additional variable or object.

如果要声明两个变量并使用单个语句内的单个表达式初始化它们,则唯一合理的语法选项如下。没有任何选项可以避免在不涉及额外变量或对象的情况下重复变量名称。

(function(){
  var bar, foo = bar = 1;
}());

It works, but it's incompatible with the ES6 constkeyword, because barisn't being assigned by the declaration (const bar), but by a sub-expression (bar = 1). There's no supported way to accomplish this with constas a single statement.

它可以工作,但它与 ES6const关键字不兼容,因为bar不是由声明 ( const bar)赋值,而是由子表达式 ( bar = 1)赋值。没有受支持的方法可以const使用单个语句来完成此操作。

(function(){
  const bar, foo = bar = 1;
}());
Uncaught SyntaxError: Missing initializer in const declaration

The multi-line version obviously has no such issue. For what it's worth, I also find it easier to read.

多行版本显然没有这样的问题。对于它的价值,我也发现它更容易阅读。

(function(){
  const foo = 1;
  const bar = foo;
}());

回答by guest271314

You could use destructing assignment

您可以使用破坏性分配

(function(){
  var [foo, bar] = [1, 1];
  console.log(foo, bar)
}());