简体   繁体   中英

Why does this Angular 6 onclick function not working properly?

So, I built a quick Angular 6 app to help estimate bill amounts given the start and end date of the period a user wants to calculate for. (ex. 1 and 5 would return the total amount of bills from the 1st to the 5th).

Anyways, I have a button run the following function when clicked (this.bills$ is the json data im using) but its not working when i enter a startDay higher than the endDay.

 estimateBills() { this.estimateText = 0; console.log('00: startDay is: ' + this.startDay + ' and, endDay is: ' + this.endDay); if (this.startDay < this.endDay) { console.log('1: startDay is: ' + this.startDay + ' and, endDay is: ' + this.endDay); for (var i = 0; i < this.bills$.length; i++) { if (this.startDay <= this.bills$[i].DueDate && this.endDay >= this.bills$[i].DueDate) { console.log('Bill DueDate is: ' + this.bills$[i].DueDate + ' and Amount is ' + this.bills$[i].Amount); this.estimateText = +this.estimateText + this.bills$[i].Amount; } } } else if (this.startDay > this.endDay) { console.log('2: startDay is: ' + this.startDay + ' and, endDay is: ' + this.endDay); for (var i = 0; i < this.bills$.length; i++) { console.log('looping'); if (this.startDay <= this.bills$[i].DueDate || this.endDay >= this.bills$[i].DueDate) { console.log('Bill DueDate is: ' + this.bills$[i].DueDate + ' and Amount is ' + this.bills$[i].Amount); this.estimateText = +this.estimateText + this.bills$[i].Amount; } } } else { this.estimateText = 1; } }

Here are some examples of what i get when run the function. For some reason it does not realize that the startDay is higher than the endDay! idk what is going wrong

When startDay is smaller than endDay (correct output)

When endDay is smaller than startDay (incorrect output)

Most probably the reason is that both this.startDay and this.endDay are strings, therefore "28" < "4" comparison is true (first characters '2' and '4' are compared in this case).

Explicit cast to numbers may help here, ie Number(this.startDay) < Number(this.endDay) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM