If-less 1 or 0 resolution in jQuery
I wish to make any number other than 160 resolve to 1, and 160 resolve to 0. 160 must resolve to exactly 1, no more, no less. Does anybody know how to do this? I don't want to use an if or else, but I'm fine with using modulus and math.abs. Thanks.
CLARIFICATION: no ternary operators, I'm looking for more of a mathemati开发者_如何学JAVAcal operation, or something ingenuitive like that.
(Note, this was before the edit)
Ternary operator (it's neither if
nor else
;)):
var value = number === 160 ? 0 : 1;
Still not math but type conversion:
var value = +(number !== 160);
Still not math but boolean operators:
var value = (number !== 160) && 1 || 0;
A little bit math and type conversion:
var value = +(!!(160 - number)); // outer brackets can probably be omitted
maybe I should stop now ;)
While not strictly mathematical operations, you can use the javascript Math
object's functions max
and min
to do this.
To get n
to resolve to 1 for 160, and 0 otherwise, you can use:
var r = Math.abs(Math.max(-1, Math.min(1, n - 160))) ;
If you want the 1 and 0 reversed, you can do:
var r1 = Math.abs(r - 1) ;
精彩评论