提问人:S.S 提问时间:12/19/2021 最后编辑:S.S 更新时间:12/19/2021 访问量:42
Javascript 类,将一个参数传递给数组;
Javascript Class, with one parameter passed to array;
问:
我正在尝试使用以下代码调用一个类:
class matchDetails {
constructor(game, kit, player){
this.game = game; // This remains static;
this.kit = color; // This remains static;
this.player = new Array(player);
}
addMatchDetails(){
// return "Coventry";
}
}
ab = new matchDetails(23, 'red', 11);
在构造函数上,我希望this.player是一个数组,我可以在其中推送其他值,但我无法弄清楚如何对其进行编码。
答:
0赞
Elson Ramos
12/19/2021
#1
最简单的方法是不断扩展您的构造器并添加线条。您可以初始化数组并推送值。请参阅以下示例:
class matchDetails {
constructor(game, kit, player){
this.game = game;
this.kit = kit;
this.player = [];
this.player.push(player)
}
addMatchDetails(){
// return "Coventry";
}
}
ab = new matchDetails(23, 'red', 'smith');
//pushing additional surnames
ab.player.push('jones');
console.log(ab)
//matchDetails { game: 23, kit: 'red', player: [ 'smith', 'jones' ] }
此外,没有“color”变量,所以我把它改成了“kit”。
评论
0赞
S.S
12/19/2021
这太完美了 - 非常感谢。
0赞
Elson Ramos
12/19/2021
@S.S 我很乐意帮助你。您可以为我的答案投赞成票以帮助其他开发人员。谢谢
评论
this.player = [player]