繁杂代码:
var index=4;
while (index--) {
switch (index) {
case 0:
this.spot0.showPoint(index);
break;
case 1:
this.spot1.showPoint(index);
break;
case 2:
this.spot2.showPoint(index);
break;
case 3:
this.spot3.showPoint(index);
break;
}
}
可以发现:对象this.spot0 , 对象this.spot1 , 对象this.spot2 , 对象this.spot3有相同部分,同时最后一个是数字且有序
简洁代码(方法一):通过方括号拼接对象名
var index=4;
while (index--) {
this["spot"+index].showPoint(index);
}
发现:通过[ ]来获取对象,批量处理对象名字有序的对象优点很明确
缺点:通过[ ]获取的对象,当你想去找方法showPoin()时,提示该方法是未定义的,维护性差一点
简洁代码(方法二):通过数组存储对象
var starItems:Array<any> = [this.spot0,this.spot1,this.spot2,this.spot3];
var index=4;
while (index--) {
starItems[index].showPoint(index);
}
缺点:通过数组存储对象,当你想去找方法showPoin()时,提示该方法是未定义的,维护性差一点
网友评论