我试图在按下按钮时按下数组中的数据,并在再次按下按钮时从数组中删除数据(并更改按钮类)。
<button
*ngFor="#color of colors"
[class.selected]="color === selectedColors"
(click)="onPress(color)">
{{color.name}}
</button>我在我的课堂上放了两种方法- onPress & hasColor
onPress(color: Color) {
this.selectedColors = color;
// ckecking color in array
if (this.hasColor(this.colorsArray,this.selectedColors.id)) {
//need to splice a color from array and change background color to default (to blue color)
} else {
// if not in colorsArray then push and change class to .selected
this.colorsArray.push(this.selectedColors.id);
}
}
hasColor(arrayC,id) {
arrayC.forEach(function(item) {
if (item === id) {
return true;
}
return false;
});
} 我该怎么做呢?hasColor方法返回真或假,但在onPress方法中不返回
发布于 2016-02-26 10:48:04
hasColor方法返回true或false
不,不是的。
传递给forEach的匿名函数返回true或false (对于循环中的每个项都是这样做的)。
hasColor函数本身根本没有返回语句。
如果要查看for循环中是否有任何项匹配,则需要使用变量跟踪以查看是否有匹配项,然后在循环结束后返回该变量。
hasColor(arrayC, id) {
var match = false;
arrayC.forEach(function(item) {
if (item === id) {
match = true;
}
});
return match;
}https://stackoverflow.com/questions/35649519
复制相似问题