简体   繁体   中英

javascript telephone dialer - keep number within a specific range

For example, A var n, initial value is 0 . When mouse being dragged, decrease n by 1, but keep n between 0 to 11. Think this like the circle-dialer on an old telephone, var n loops between 0-11. I've tried abs, min and max, none of them works. Is there any method to achive this? just point me in a direction or any keywords would be appreciated.

Many thanks.

var n =0;
function mouseDragged() {
n-=1; 

console.log(n);
//as long as console.log keeps showing 0-11, the problem is solved
}

I presume mouseDragged needs a parameter that tells it whether to increment or decrement n . In this example, I will pass in a boolean increment flag.

var n = 0;

function mouseDragged(increment) {
  if (increment) {
    if (n < 11) {
      n += 1;
    }
  } else if (n > 0) {
      n -= 1;
  }
  console.log(n);
}

[UPDATE]

On the other hand, if you never want to increment, but you also want to be able to loop around from 0 back up to 11, then this should work:

var n = 0;

function mouseDragged() {
  if (n > 0) {
    n -= 1;
  } else {
    n = 11;
  }

  console.log(n);
}

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