我正在尝试创建具有以下要求的函数pluralizeParam(n,word,pluralWord):
如果n为1,则返回非复数词(参数词);否则,在复数词后添加“ s”;
如果提供了pluralWord参数,则不添加“ s”,而是返回pluralWord。
到目前为止,我所做的是:
function returnPluralWord(n, word, pluralWord) {
if (n === 1) {
return word;
} else if (n === 1 && (word.lastIndexOf("s")) || (word.lastIndexOf("ess"))) {
return word + "s";
} else if (n !== 1 && word.length - 2 === "es") {
return word + "s";
} else if (pluralWord !== 'undefined') {
return pluralWord;
}
}
var result = returnPluralWord(2, "lioness", "lionesses");
console.log(result);
我的问题是:它不打印复数字。我怎么做?
谢谢
最佳答案
word.length - 2
永远不能等于"es"
。您还需要重新排列语句,第二个已经被1捕获了。
当您使用word.lastIndexOf('s')
(我认为这是错误的逻辑)时,它将返回s
字符的最后一个索引,而不是如果它以s
结尾。
您可以检查String#endsWith和String#startsWith方法,这些方法检查字符串是否以给定部分开头或结尾
const str = 'less';
console.log(str.endsWith('s'))
关于javascript - 如何在javascript中的函数内部打印参数值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46715338/