conditional - (Javascript) multiple condition set for ternary operator issue -
for (var days = 1; days <= 31; ++days) { console.log( (days == (1, 31, 21) ? days + 'st':'') || (days == (2, 22) ? days + 'nd':'') || (days == (3, 23) ? days + 'rd':'') || days + 'th' ); }
trying display (1st, 2nd, 3rd)
(21st, 22nd, 23rd)
(31st)
(multiple th)
i'm getting strange result here, i'm not quite sure i've done wrong, appreciated.
i did try google , figure out, promise, appreciate relatively detailed explanation why behaving strange.
you've typed in code syntactically correct, doesn't mean apparently expect mean.
this:
(days == (1, 31, 21) ? days + 'st':'')
is in effect same as
(days == 21 ? days + 'st':'')
the (1, 31, 21)
subexpression involves comma operator, allows sequence of expressions (possibly side-effects) evaluated. overall value value of last expression.
if want compare value list of possibilities, in general can
- use sequence of
==
(or===
) comparisons connected||
; - use
switch
statement groups ofcase
clauses; - use
.indexof()
value in array.
in particular case, i'd make array containing suffixes , index it:
var suffixes = array.apply(null, new array(32)).map(function() { return "th"; }); suffixes[2] = suffixes[22] = "nd"; suffixes[1] = suffixes[21] = suffixes[31] = "st"; suffixes[3] = suffixes[23] = "rd";
then can index array day number suffix.
Comments
Post a Comment