最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript prevent decrement past 0 - Stack Overflow

programmeradmin1浏览0评论

Probably a rookie question, but how do I prevent the decrement from going past zero into the negative numbers?

public counter : number = 0;
increment(){
  this.counter += 1;
}

decrement(){
  this.counter -= 1;
}

Probably a rookie question, but how do I prevent the decrement from going past zero into the negative numbers?

public counter : number = 0;
increment(){
  this.counter += 1;
}

decrement(){
  this.counter -= 1;
}
Share Improve this question edited Feb 23, 2020 at 19:56 tadman 212k23 gold badges235 silver badges265 bronze badges asked Feb 23, 2020 at 19:54 pjleinenpjleinen 791 gold badge1 silver badge5 bronze badges 3
  • 2 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Quentin Commented Feb 23, 2020 at 19:55
  • Is this TypeScript? – tadman Commented Feb 23, 2020 at 19:56
  • there is no way to prevent decrement (--) or subtraction assignment (-=) from going below 0. Apply logic to determine whether or not you need to modify the value in first place – Max Commented Feb 23, 2020 at 20:19
Add a comment  | 

4 Answers 4

Reset to default 13

For clarity, I suggest to use the Math.max() function to make sure that the value is always greater than or equal to 0.

decrement(){
  this.counter = Math.max(0, this.counter - 1);
}

This is not the fastest way to do this but as long as you don't call decrement() in a loop for several hundred thousand times, the performance degradation is too small to be perceived.

You simply check if the counter is still greater than zero and only if so you actually decrement your counter

decrement(){
  if(this.counter > 0){
    this.counter -= 1
  }
}

Write the function to clamp it at zero:

decrement(){
  this.counter -= 1;
  if (this.counter < 0) {
     this.counter = 0;
  end
}

you can do it using ternary operator too.

value > 0 ? value - 1 : 0
发布评论

评论列表(0)

  1. 暂无评论