📜  如何根据 JavaScript 中的输入数字返回单词的单数/复数形式?

📅  最后修改于: 2021-11-07 08:57:47             🧑  作者: Mango

在本文中,我们将学习如何根据输入的数字返回单词的单数或复数形式。这可用于需要根据值动态更改单词的情况。这可以使用两种方法来实现。

方法 1:将单词的单复数形式都传递给函数。在这种方法中,可以创建一个简单的函数,该函数接受单词的单数和复数版本以及计数值,并根据计数返回适当的单词。我们可以使用三元运算符(?) 来检查所需的计数。

句法:

function pluralizeWord(singularWord, pluralWord, count) {
  return count > 1 ? pluralWord : singularWord;
}

示例 1:

HTML


  

    GeeksforGeeks   

       How to return the singular or plural     form of the word based on the input     number in JavaScript?      


HTML


  

    GeeksforGeeks   

       How to return the singular or plural     form of the word based on the input      number in JavaScript?      


输出:

1 "geek"
4 "geeks"
4 "spies"
1 "man"
4 "men"

方法 2:创建一个包含单词的所有可能复数版本的词典。如果代码中重复了很多单词,则上述方法效率低下。我们可以通过创建一个单词复数字典并在检查计数后使用该字典选择合适的单词来解决这个问题。

句法:

let pluralDict = {
      "geek": "geeks",
      "spy": "spies",
      "foot": "feet",
      "woman": "women"
    }


function pluralizeWord(singularWord, count) {
  return count > 1 ? pluralDict[singularWord] : singularWord;
}

示例 2:

HTML



  

    GeeksforGeeks   

       How to return the singular or plural     form of the word based on the input      number in JavaScript?      

输出:

4 "geeks"
 1 "geek"
 4 "spies"
 1 "woman"
 4 "feet"