在 Map 对象中插入键/值时出错,使用 forEach ()



我创建了一个类来在我的 Map 中注册点,但是当使用 forEach (( 循环时,什么都没有返回

class PtsPeriods {
constructor( ptsFrist=0, ptsSecund=0, ptsThird=0 )  { 
const periods = new Map();
let args = [...arguments];

args.forEach((cur, index) => { periods.set(index++,cur);})

}
};

记录数据:

const AllTeams = new Map();
function registerTeam(simbol=" ", team, pts1, pts2, pts3) {
AllTeams.set(`${simbol} ${team}`, new PtsPeriods(pts1,pts2,pts3));
}
registerTeam("🐃","bulls",10,20,30);
console.log(AllTeams);

日志中的结果Map (1) {"🐃 bulls" => Pt Periods}PtsPeriods为空对象。

{"🐃 bulls" => PtsPeriodo}
key: "🐃 bulls"
value: PtsPeriodo {}

预期结果是

{"🐃 bulls" => Map (3)}
key: "🐃 bulls"
value: Map (3) {1 => 10, 2 => 20, 3 => 30}

问题是你的类构造函数没有为实例赋值,它只创建一个空对象,你应该改变你的构造函数:

class PtsPeriods {
constructor( ptsFrist=0, ptsSecund=0, ptsThird=0 )  { 
this.periods = new Map();
let args = [...arguments];

args.forEach((cur, index) => { this.periods.set(index++,cur);})

}
};

这样,您将值分配给类实例。

相关内容

最新更新