Reputation: 923
What is the cleanest way to check whether some variable X is within n numbers of some variable Z. n is an arbitrary defined number (i.e. 3).
So I want the
if (z {something} x){
// run code if x and z are within 3 of each other
}
Upvotes: 0
Views: 62
Reputation: 2973
Calculate the absolute value of the difference of z and x. http://www.w3schools.com/jsref/jsref_abs.asp
if ((Math.abs(z-x) <= 3){
// do something
}
Upvotes: 0
Reputation: 386883
You could use the absolute difference of the value and check it.
if (Math.abs(x - z) < 3) {
Upvotes: 2