assign multiple variables to the same value in Javascript

前端 未结 5 2013
Happy的楠姐
Happy的楠姐 2020-11-30 18:40

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

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


        
5条回答
  •  隐瞒了意图╮
    2020-11-30 18:55

    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 other way 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 const variables to the same value on a single line all with the same expected scope.

    References:

    • MDN: Array Global Object

    • MDN: Array.fill

提交回复
热议问题