ES6 Class - 映射变量数组

ES6 Class - map array of variables

假设我有一个包含 5 个人名的列表

let listNames = [Sam, Ash, Moe, Billy, Kenzi]

并且我希望每个名称都具有 doneHomeWorklazy 的属性,使用 class

class Person {
    constructor() {
        this.doneHomeWork = 0
        this.lazy = false
    }
}

而不是像这样分配每个名称:

const Sam = new Person()
const Ash = new Person()
const Moe = new Person()
const Billy = new Person()
const Kenzi = new Person()

我正在考虑这样做

listNames.forEach(name => {
    name = new Person()
})

但是,在我的 ESLint 中它给我一个错误

Assignment to function parameter 'name' no-param-reassign

这看起来微不足道,但出于某种原因,我无法重构它。

问题是名称变量是用于在循环内循环的变量。 您正在循环的第一次迭代中更改此值。这就是你的错误 Assignment to function parameter 'name' no-param-reassign.

的原因

那么您正在尝试使用动态名称作为变量名称。如果你想这样做,方法是使用括号表示法,所以你可以这样做:

class Person {
    constructor() {
        this.doneHomeWork = 0
        this.lazy = false
    }
}
let persons = [];
let listNames = ['Sam', 'Ash', 'Moe', 'Billy', 'Kenzi'];

correctListNames.forEach(name => {
    persons[name] = new Person()
})

console.log(persons);

您可以使用 ES6 数组解构并将 Person class 的新实例分配给每个名字。

class Person {
  constructor() {
    this.doneHomeWork = 0;
    this.lazy = false;
  }
}


const [Sam, Ash, Moe, Billy, Kenzi] = Array.from(Array(5), e => new Person)

console.log(Sam)
console.log(Ash)

而不是尝试动态生成这个

const Sam = new Person();
const Randy = new Person():

你可以通过这样得到类似的东西,

const persons = {
  Sam: new Person(),
  Randy: new Person(),
};

然后您可以使用 persons['Sam']persons.Sam 访问它们。 现在要从数组中实现这一点,

const arr = ['Sam', 'Randy'];
const persons = {};
arr.forEach(name => {
  persons[name] = new Person();
});

As for the eslint warning that you are getting is because you are trying to change the value of a parameter of a function. You can turn if off by setting the rule to 0 in your eslint configuration file. However I would recommend not to turn if off.

你可以使用 ES6 的解构特性来实现:

class Person {
    constructor() {
        this.doneHomeWork = 0
        this.lazy = false
    }
}
let arr = [];
for(let i=0;i<6;i++) {
 arr.push(new Person());
}


const [Sam, Ash, Moe, Billy, Kenzi] = [...arr];

console.log(Sam);