javascript 在Javascript中将多个变量分配给相同的值

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

assign multiple variables to the same value in Javascript

javascript

提问by karthikr

I have initialized several variables in the global scope in a JavaScript file:

我在 JavaScript 文件的全局范围内初始化了几个变量:

var moveUp, moveDown, moveLeft, moveRight;
var mouseDown, touchDown;

I need to set all of these variables to false, this is the code I currently have:

我需要将所有这些变量设置为 false,这是我目前拥有的代码:

moveUp    = false;
moveDown  = false;
moveLeft  = false;
moveRight = false
mouseDown = false;
touchDown = false;

Is there any way that I can set all of these variables to the same value in one line of code, or is the code I currently have the best way to do this

有什么方法可以在一行代码中将所有这些变量设置为相同的值,或者我目前有最好的方法来做到这一点

回答by karthikr

Nothing stops you from doing

没有什么能阻止你做

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

检查这个例子

var a, b, c;
a = b = c = 10;
console.log(a + b + c)

回答by Govind Rai

Nothing stops you from doing the above, but hold up!

没有什么能阻止你做上面的事情,但是坚持下去!

There are some gotchas. Assignment in Javascript is from right to left so when you write:

有一些问题。Javascript 中的赋值是从右到左,所以当你写的时候:

var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

it effectively translates to:

它有效地转化为:

var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));

which effectively translates to:

这有效地转化为:

var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));

Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.

无意中,您刚刚创建了 5 个全局变量——我很确定您不想这样做。

Note: My above example assumes you are running your code in the browser, hence window. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to globalwhich is the global context for that environment).

注意:我上面的例子假设你在浏览器中运行你的代码,因此window. 如果您在不同的环境中,这些变量将附加到该环境的全局上下文(即,在 Node.js 中,它将附加到global该环境的全局上下文)。

Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.

现在您可以先声明所有变量,然后将它们分配给相同的值,这样就可以避免这个问题。

var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.

长话短说,两种方式都可以正常工作,但第一种方式可能会在您的代码中引入一些有害的错误。如果不是绝对必要,不要犯用局部变量乱扔全局命名空间的罪过。



Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.

旁注:正如评论中所指出的(这不仅仅是在这个问题的情况下),如果有问题的复制值不是原始值而是一个对象,您最好了解按值复制与按引用复制。每当分配对象时,都会复制对对象的引用而不是实际对象。所有变量仍将指向同一个对象,因此一个变量的任何更改都将反映在其他变量中,如果您打算复制对象值而不是引用,这将给您带来很大的麻烦。

回答by Doug Coburn

There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.

当尝试将多个变量初始化为相同值时,还有另一个选项不会引入全局问题。它是否比长路更可取是一个判断力。它可能会更慢,并且可能会或可能不会更具可读性。在您的具体情况下,我认为很长的路可能更具可读性和可维护性,并且速度更快。

The otherway utilizes Destructuring assignment.

其他方式使用解构赋值

let [moveUp, moveDown,
     moveLeft, moveRight,
     mouseDown, touchDown] = Array(6).fill(false);

console.log(JSON.stringify({
    moveUp, moveDown,
    moveLeft, moveRight,
    mouseDown, touchDown
}, null, '  '));

// NOTE: If you want to do this with objects, you would be safer doing this
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));
console.log(JSON.stringify({
    obj1, obj2, obj3
}, null, '  '));
// So that each array element is a unique object

// Or another cool trick would be to use an infinite generator
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();
console.log(JSON.stringify({
    a, b, c, d
}, null, '  '));

// Or generic fixed generator function
function* nTimes(n, f) {
    for(let i = 0; i < n; i++) {
        yield f();
    }
}
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];
console.log(JSON.stringify({
    p1, p2, p3
}, null, '  '));

This allows you to initialize a set of var, let, or constvariables to the same value on a single line all with the same expected scope.

这使您可以初始化一组varletconst在一行中的变量相同的值都具有相同的预期范围。

References:

参考:

回答by Tohamas Brewster

Put the varible in an array and Use a for Loop to assign the same value to multiple variables.

将变量放入数组并使用 for 循环将相同的值分配给多个变量。

  myArray[moveUP, moveDown, moveLeft];

    for(var i = 0; i < myArray.length; i++){

        myArray[i] = true;

    }