【问题标题】:ESLint throws an error when trying to assign multiple variables to the same value尝试将多个变量分配给相同的值时,ESLint 会引发错误
【发布时间】:2020-09-17 06:55:59
【问题描述】:

为什么 ESLint 在这行代码的a 变量声明之后抛出了Parsing error: Unexpected token ,

const a, b, c = 1;

我的.eslintrc.json 看起来像这样;

{

    "env": {
        "browser": true,
        "es6": true,
        "jquery": true,
        "commonjs": true
    },
    "extends": [
        "airbnb-base",
        "prettier"
    ],
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "script"
    },
    "plugins": ["prettier"],
    "rules": {
        "prettier/prettier": "error",
        "semi": ["error", "always"],
        "quotes": ["error", "double"]
    }

}

【问题讨论】:

  • 因为它不喜欢串行分配。您可以根据需要更改规则。
  • 这不是有效的 JavaScript。尝试将const a, b, c = 1; 复制并粘贴到控制台中。我收到了Uncaught SyntaxError: Missing initializer in const declaration
  • @jmargolisvt 在 JS 中无效,不能随便改 JavaScript 的规则...
  • 糟糕。读错了。

标签: javascript eslint


【解决方案1】:

你不能在 JS 中这样做。

如果变量声明中列出了多个变量(varletconst),每个值都有自己的初始化器,因此不可能在单个声明语句中为多个变量分配单个值,不重复。

如果缺少初始化程序(不存在 = value 部分),则变量将设置为 undefined

因此,如果您使用let,那么c 将变为1,而ab 将变为undefined

let a, b, c = 1;

console.log(a, b, c) //undefined undefined 1

但是,在 const 声明中省略初始化程序会引发错误(将 undefined 分配给常量没有太大意义,对吧?)

因此,您的代码会失败(不仅在 ESLint 中,在任何正确实现 ECMAScript 标准的 JS 运行时中):

const a, b, c = 1; //SyntaxError

要将相同的值分配给多个变量,您必须:

  • 重复值(如果值是对象字面量(包括数组字面量和函数表达式)或由构造函数、工厂或非纯函数返回,这将不起作用):

    const a = 1, b = 1, c = 1;
    
    console.log(a, b, c) //1 1 1
  • 相互分配变量(提示:将名称最短的放在前面,然后重复那个):

    const a = 1, b = a, c = a;
    
    console.log(a, b, c) //1 1 1
  • 使用let:

    let a, b, c;
    a = b = c = 1
    
    console.log(a, b, c) //1 1 1
  • 解构一个无限迭代器(这在变量非常多的情况下似乎很有用):

    const [a, b, c] = (function*(v){while(true) yield v})(1);
                                                       // ^--- Value
    
    console.log(a, b, c) //1 1 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 2014-06-30
    • 2013-04-27
    • 2019-01-27
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多