我在一个JavaScript文件中初始化了全局作用域中的几个变量:

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

我需要把所有这些变量都设为false。这是我目前拥有的代码:

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

是否有任何方法,我可以设置所有这些变量的相同值在一行代码,或者是代码我目前有最好的方式来做到这一点?


当前回答

没有什么能阻止你这样做,但是坚持住!

这里有一些陷阱。在Javascript中赋值是从右向左的,所以当你写:

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

它有效地翻译为:

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

这句话的意思是:

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

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

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

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

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

长话短说,两种方法都可以很好地工作,但是第一种方法可能会在代码中引入一些有害的错误。如果不是绝对必要,不要在全局名称空间中使用局部变量。


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.

其他回答

在Javascript中分配多个变量到相同的值?

let a=10
let b=10
let c=10
let d=10
let e=10
console.log(a,b,c,d,e)

我个人总是尽量避免var,总是使用let和const,我从发生的错误和大多数最佳实践建议中学到了它,所以下面在评论中提到,但更准确地说:

function good() {  
    let a;
    let b;
    let c;
    let d;        
    a = b = c = d = 'hello';    
    console.log(d);    
}

function bad() {
    //only the first variable is declared as local
    let a = b = c = d = 'bye';
    console.log(d)
}

let a;
let d;

good();
bad();

//expected undefined
console.log(a);

//expected bye 
console.log(d);

您所列出的原始变量可以在使用解构赋值的短代码行中声明并赋值给相同的值。关键字let、const和var都可以用于这种类型的赋值。

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

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

  myArray[moveUP, moveDown, moveLeft];

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

        myArray[i] = true;

    }

如果你想声明多个const变量,你可以通过

const [a, b, c, d] = [[], [], [], []]

同时分配空对象或任何值。