Javascript通过解构重新分配let变量

plm*_*k61 34 javascript ecmascript-6 eslint

在我的React应用程序中,我使用的是airbnb的eslint样式指南,如果我不使用destructuing则会抛出错误.

在下面的情况中,我首先使用let分配两个变量latitudelongitude位置对象数组中第一个项的坐标.然后,如果用户允许我访问他们的位置,我会尝试使用解构来重新分配他们的值.

let latitude = locations[0].coordinates[1];
let longitude = locations[0].coordinates[0];

if (props.userLocation.coords) {
  // doesn't work - unexpected token
  { latitude, longitude } = props.userLocation.coords;

  // causes linting errors
  // latitude = props.userLocation.coords.latitude;
  // longitude = props.userLocation.coords.longitude;
}
Run Code Online (Sandbox Code Playgroud)

内部解构if语句导致的unexpected token错误.

以旧式方式重新分配变量会导致ESlint: Use object destructuring错误.

Jon*_*lms 79

 ({ latitude, longitude } = props.userLocation.coords);
Run Code Online (Sandbox Code Playgroud)

解构需要在a 或声明之后let,const或者var需要在表达式上下文中,以区别于块语句.

  • 如果您使用现代 JS 并且通常省略分号,在这种情况下,您必须在语句之前或上一行的末尾添加分号。否则,括号表达式将被解释为对前一行的右值的函数调用。 (14认同)
  • 以前从未见过,谢谢 (12认同)