我试图在按下按钮时将数据推送到数组中,并在再次按下按钮时将其从数组中删除(并更改按钮类)。
<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 方法返回 true 或 false,但在 onPress 方法中永远不会返回
最佳答案
hasColor method returns true or false
不,事实并非如此。
传递给 forEach
的匿名函数返回 true
或 false
(并对循环中的每个项目执行此操作)。
hasColor
函数根本没有自己的 return 语句。
如果您想查看 for 循环中是否有任何项匹配,那么您需要使用一个变量来跟踪是否有任何匹配项,然后在循环后返回该变量结束。
hasColor(arrayC, id) {
var match = false;
arrayC.forEach(function(item) {
if (item === id) {
match = true;
}
});
return match;
}
关于javascript - 如何切换按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35649519/