当尝试将多个变量初始化为相同的值时,还有另一个选项不会引入全局陷阱。这条路是否比远路更可取,这是一个判断。它可能会更慢,并且可能更具可读性。在您的具体情况下,我认为长距离可能更具可读性和可维护性,而且速度更快。
另一种方法使用解构赋值。
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, ' '));
这允许您将一组var、let或const变量初始化为具有相同预期作用域的单行上的相同值。
引用:
MDN:数组全局对象
MDN: Array.fill