我是新人&在exercism.io上执行此exercise,我正在尝试将值对推入对象,到目前为止我的代码:
class School{
constructor(){
this.rosterList = {};
}
roster(){
return this.rosterList;
}
add(name,grade){
let nameArry = [];
this.rosterList.grade = nameArry.push(name);
}
}
let a = new School;
a.add('Aimee', 2)
console.log(a.roster());
导致
{等级:1}
我试图获得的结果
{2:['Aimee']}
我的问题是阵列成为1的原因?如何将名称推入类似数组应该?如何将“2”推入内部,而不是“等级”,谢谢
答案 0 :(得分:2)
您正在获得输出{grade : 1}
,因为在行中:
this.rosterList.grade = nameArry.push(name);
您只是将propA等级指定为nameArry.push(name)的返回值,push方法返回数组的长度,在您的情况下为1。
要获得所需的结果,请将此行更改为:
nameArry.push(name);
this.rosterList[grade] = nameArry;
答案 1 :(得分:2)
您需要检查密钥是否存在,然后按下或分配值,如下所示,使用括号表示法this.rosterList[grade]
来设置密钥。
注意,当使用Arry.push(value)
进行分配时,您将获得数组的长度,而不是数组本身。
Stack snippet
class School{
constructor(){
this.rosterList = {};
}
roster(){
return this.rosterList;
}
add(name,grade){
this.rosterList[grade] ?
this.rosterList[grade].push(name) :
this.rosterList[grade] = [name];
}
}
let a = new School;
a.add('tom', 2)
a.add('amy', 2)
console.log(a.roster());
您可以使用ternary
,而不是使用concat
运算符
add(name,grade){
this.rosterList[grade] = (this.rosterList[grade]||[]).concat(name);
}
答案 2 :(得分:1)
您可以使用this.rosterList[grade].concat([name])
附加为特定成绩的现有数组添加新名称。如果grade
的数组不存在,那么您可以初始化this.rosterList[grade] = []
。请参阅下面的工作代码:
class School{
constructor(){
this.rosterList = {};
}
roster(){
return this.rosterList;
}
add(name,grade){
if(!this.rosterList[grade]) this.rosterList[grade]=[];
this.rosterList[grade] = this.rosterList[grade].concat([name]);
}
}
let a = new School;
a.add('tom', 2);
a.add('Aimee', 2);
console.log(a.roster());
答案 3 :(得分:0)
array.push()
返回数组的新长度,因此您无法在一行中执行此操作。但您可以在创建数组时直接添加值。
要使用变量作为键,您必须使用[]
表示法。
class School {
constructor() {
this.rosterList = {};
}
roster() {
return this.rosterList;
}
add(name, grade) {
let nameArry = [name];
this.rosterList[grade] = nameArry;
}
}
let a = new School();
a.add('tom', 2)
console.log(a.roster());