使用for循环将项目推送到数组

时间:2018-02-20 13:19:31

标签: javascript

我想使用for循环向数组中添加项目,但不知怎的,我无法使用变量i来定义被“推送”的项目。我的解决方法如下所示:

if (this.antwortenNG == 1){
  this.frageObject.antwort.push(this.antwort1);
} else if(this.antwortenNG == 2){
  this.frageObject.antwort.push(this.antwort1);
  this.frageObject.antwort.push(this.antwort2);
}else if(this.antwortenNG == 3){
  this.frageObject.antwort.push(this.antwort1);
  this.frageObject.antwort.push(this.antwort2);
  this.frageObject.antwort.push(this.antwort3);
}else if(this.antwortenNG == 4){
  this.frageObject.antwort.push(this.antwort1);
  this.frageObject.antwort.push(this.antwort2);
  this.frageObject.antwort.push(this.antwort3);
  this.frageObject.antwort.push(this.antwort4);
}else if(this.antwortenNG == 5){
  this.frageObject.antwort.push(this.antwort1);
  this.frageObject.antwort.push(this.antwort2);
  this.frageObject.antwort.push(this.antwort3);
  this.frageObject.antwort.push(this.antwort4);
  this.frageObject.antwort.push(this.antwort5);
}

但我想让它更短,所以我试图创建一个for循环,但我不知道我不能使用变量i来添加项目。无论如何要解决这个问题吗?

for(var i = 1; i <= this.antwortenNG; i++){
  this.frageObject.antwort.push(this.antwort+i);
}

0 个答案:

没有答案