Angular 5中如何根据HP条件跳过数组元素并置灰展示
我明白你遇到的问题了——把比较操作写成赋值确实会不小心修改数据,咱们一步步来修复这个问题,同时实现跳过HP为0的参与者、置灰这些需求。
解决方法:跳过HP为0的参与者并置灰元素
第一步:修复模板,实现HP为0时置灰
首先在模板里,我们需要给HP为0的参与者添加一个置灰的CSS类,同时保证选中状态的样式优先级。优化原有的类绑定逻辑,让代码更清晰:
<div class="heroWrapper"> <div class="image hero" *ngFor="let participant of participants; index as i" [class.selected]="i === selectedParticipant" [class.grayed-out]="participant.hitPoints === 0"> <img [src]="participant.imageUrl" (click)="toggleMoves = !toggleMoves"/> <span [ngStyle]="{'color': getColor(participant)}" class="HP">{{participant.hitPoints}}</span> <span class="namePlayer" *ngIf="isHero(participant)">{{getPlayerName(participant)}}</span> <span class="nameHero">{{participant.name}}</span> </div> </div>
然后在CSS里定义grayed-out类的样式,实现置灰效果:
.grayed-out { opacity: 0.5; pointer-events: none; /* 可选:禁用点击交互,避免玩家操作已阵亡的角色 */ }
第二步:修复Next/Previous方法,跳过HP为0的参与者
核心是要循环查找下一个/上一个HP不为0的参与者(毕竟可能连续多个角色HP为0),我们可以写两个辅助函数来复用逻辑,同时彻底避免赋值/比较的低级错误。
1. 添加辅助查找函数
在组件类里添加两个私有辅助函数,专门用来找到有效的切换目标:
private findNextValidIndex(currentIndex: number): number { let nextIndex = currentIndex; do { // 循环移动索引:到达末尾就回到开头 nextIndex = nextIndex === this.participants.length - 1 ? 0 : nextIndex + 1; // 终止条件:找到HP>0的角色,或者遍历完所有角色(防止全阵亡的死循环) if (this.participants[nextIndex].hitPoints > 0 || nextIndex === currentIndex) { break; } } while (true); return nextIndex; } private findPreviousValidIndex(currentIndex: number): number { let prevIndex = currentIndex; do { // 循环移动索引:到达开头就回到末尾 prevIndex = prevIndex === 0 ? this.participants.length - 1 : prevIndex - 1; // 终止条件:找到HP>0的角色,或者遍历完所有角色 if (this.participants[prevIndex].hitPoints > 0 || prevIndex === currentIndex) { break; } } while (true); return prevIndex; }
2. 修改切换方法
现在把你的next()和previous()改成调用辅助函数,逻辑更简洁可靠:
next() { this.selectedParticipant = this.findNextValidIndex(this.selectedParticipant); this.toggleMove(); } previous() { this.selectedParticipant = this.findPreviousValidIndex(this.selectedParticipant); this.toggleMove(); }
关键错误复盘
你之前的错误代码if (this.participants[selectedParticipant].hitPoints = 0)是赋值操作,会直接把该参与者的HP设为0,然后因为赋值结果是0(在布尔判断中为false),导致后续逻辑完全不符合预期。记住:判断相等要用==/===,赋值才用=,以后写条件判断时多留意这个细节。
内容的提问来源于stack exchange,提问作者Audiosleef
相关产品推荐
相关产品推荐

