How do I write a if and if-else statement in Angular project? It's only the "else" that is returning, even though the initial conditions are true.
export class HomeComponent implements OnInit {
productWorth: number;
unit: number;
pricePerProduct:any = this.changepricePerProduct();
result: number;
constructor() {}
ngOnInit() {}
changepricePerProduct() {
if (this.productWorth >= 200 && (this.productWorth) <= 2000) {
return 150;
} else if (this.productWorth >= 2001 && (this.productWorth) <= 5000) {
return 450
} else if (this.productWorth >= 5001 && (this.productWorth) <= 10000) {
return 900
} else if (this.productWorth >= 10001 && (this.productWorth) <= 20000) {
return 1200
} else if (this.productWorth >= 20000) {
return 1500
} else {
return 0
}
}
multiply() {
this.result = this.pricePerProduct * this.unit;
}
}
CodePudding user response:
Your code doesn't show any kind of change of the productWorth
field. Hence we can just assume, that it keeps being undefined
, which will always result into 0.
Please don't mind me giving you a recommendation along. Remove this horror if-else construct. Instead you can do this:
// must be sorted
var myPriceTable = {
200: 150,
2001: 450,
5001: 900,
10001: 1200,
20001: 1500
}
function changepricePerProduct(productWorth) {
if (typeof productWorth !== 'number') return 0;
var floorKey = Object.keys(myPriceTable).findLast(key => key < productWorth);
return floorKey ? myPriceTable[floorKey] : 0;
}
console.log(changepricePerProduct(undefined));
console.log(changepricePerProduct(5));
console.log(changepricePerProduct(222));
console.log(changepricePerProduct(5555));
console.log(changepricePerProduct(22222));
CodePudding user response:
changepricePerProduct() {
return this.productWorth >= 200 && (this.productWorth) <= 2000 ? 150 :
(this.productWorth >= 2001 && (this.productWorth) <= 5000)?450:
(this.productWorth >= 5001 && (this.productWorth) <= 10000)?900:
(this.productWorth >= 10001 && (this.productWorth) <= 20000)?1200:
(this.productWorth >= 20000)?1500:0 }