简体   繁体   中英

(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 to display (1st, 2nd, 3rd) (21st, 22nd, 23rd) (31st) (multiple th) however I'm getting a strange result here, I'm not quite sure what I've done wrong, any help will be appreciated.

I did try to google and figure this out, promise, just would appreciate a relatively detailed explanation as to why its behaving strange.

You've typed in some code that is syntactically correct, but it doesn't mean anything like what you apparently expect it to mean.

This:

(days == (1, 31, 21) ? days + 'st':'')

is in effect exactly the same as

(days == 21 ? days + 'st':'')

The (1, 31, 21) subexpression involves the comma operator, which allows a sequence of expressions (possibly with side-effects) to be evaluated. The overall value is the value of the last expression.

If you want to compare a value to a list of possibilities, in general you can

  • use a sequence of == (or === ) comparisons connected by || ;
  • use a switch statement with groups of case clauses;
  • use .indexOf() to look for a value in an array.

In this particular case, I'd probably make an array containing the suffixes and then index into 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 you can just index into the array by day number to get the suffix.

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