简体   繁体   English

(Javascript)为三元运算符问题设置的多个条件

[英](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. 试图显示(1st, 2nd, 3rd) (21st, 22nd, 23rd) (31st) (multiple th)然而我在这里得到一个奇怪的结果,我不太确定我做错了什么,任何帮助都会不胜感激。

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. (1, 31, 21) 1,31,21 (1, 31, 21)子表达式涉及逗号运算符,它允许计算一系列表达式(可能带有副作用)。 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; 使用带有case子句组的switch语句;
  • use .indexOf() to look for a value in an array. 使用.indexOf()来查找数组中的值。

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. 然后,您可以按天数索引数组以获取后缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM