ESLint throws an error when trying to assign multiple variables to the same value

有些话、适合烂在心里 提交于 2021-02-15 07:35:47

问题


Why does ESLint throw a Parsing error: Unexpected token , after a variable declaration on this line of code?

const a, b, c = 1;

My .eslintrc.json looks like this;

{

    "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"]
    }

}

回答1:


You cannot do that in JS.

If multiple variables listed in a variable declaration (either var, let or const), each value has its own initializer, so it's impossible to assign a single value to multiple variables in a single declaration statement, without repetition.

If an initializer is missing (no = value part present), the variable will be set to undefined.

So if you used let, then c would become 1, while a and b would be undefined:

let a, b, c = 1;

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

However, omitting the initializer in a const declaration throws an error (it doesn't make too much sense to assign undefined to a constant, right?)

Therefore, your code fails (not just in ESLint, but in any JS runtime that correctly implements the ECMAScript standard):

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

To assign the same value to multiple variables, you have to either:

  • Repeat the value (this won't work if the value is an object literal (including array literals and function expressions) or returned by a constructor, a factory, or non-pure function):

    const a = 1, b = 1, c = 1;
    
    console.log(a, b, c) //1 1 1
  • Assign the variables from each other (tip: put the one with the shortest name first and repeat that one):

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

    let a, b, c;
    a = b = c = 1
    
    console.log(a, b, c) //1 1 1
  • Destructure an infinite iterator (that seems useful in case of a very large number of variables):

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


来源:https://stackoverflow.com/questions/62090461/eslint-throws-an-error-when-trying-to-assign-multiple-variables-to-the-same-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!