简体   繁体   中英

Making a value plural (Greater than, Less than) in Javascript

I have the following code:

    $(function(){
          var total_click = 0;
          $("#mapKey a.showKey").click(function(){
            total_click = total_click + 1;
            $("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
          });
        });

I'm trying to have it output as such:

Clicked once: "I cheated 1 whole time."

Clicked more than once: "I cheated X whole times."

-- With an 's' at the end of "times".

The counter is working fine, it's just the last part making the "time" or "times" show up appropriately that I am having difficulty with.

Any ideas what I'm doing wrong?

Thanks!

Here is your problem: total_click = 1 . Try changing it to total_click == 1 . I don't see why you have that conditional in there however, as it won't work as you expect anyway. Try $("#counter").text("I cheated " + total_click + " whole time" + ((total_click == 1)? ' ': 's '));

It's okay to use suggested implementations for a trivial cases, however it will not scale for a bigger set of problems and will not work for multiple languages (or it will get ugly very fast).

With this in mind, I've created a very simple JavaScript library that can be used to pluralize words in almost any language. It transparently uses CLDR database for multiple locales. It's API is very minimalistic and integration is extremely simple. It's called Numerous .

I've also written a small introduction article to it: « How to pluralize any word in different languages using JavaScript? ».

Feel free to use it in your project. I will also be glad for your feedback on it!

You are not using the ternary operator correctly, and also assigning total_click to 1 instead of checking its value. I would suggest moving this to a function to simplify things.

function pluralize(singular, times) {
    if (times == 1) return singular;
    else return singular + 's';
}

Then change the string to

var text = "I cheated " + clicks + " whole " + pluralize("time", clicks);

Here's an example .

  $(function(){
          var total_click = 0;
          $("#mapKey a.showKey").click(function(){
            total_click = total_click + 1;
            $("#counter").text("I cheated " + total_click + " whole " + (total_click == 1 ? "time" : "times");
return false;
          });
        });

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