繁体   English   中英

三元运算符如何在函数中工作?

[英]How does ternary operator work in the function?

您能告诉我该算法的返回线吗?

该函数应该采用字符串并返回它的Pig Latin版本,即它采用第一个辅音或辅音簇并将其放置在字符串的末尾,并在末尾添加“ ay”。

如果字符串以元音开头,则应该在末尾添加“ way”。

function translatePigLatin(str) {
  function check(obj) {
      return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj;
  }

  return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
}

// test here
translatePigLatin("consonant"); // should return "onsonantcay"

很难理解,因为名称太可怕了。 obj实际上是一个用于移至字符串中某个位置的数字,因此应将其命名为pos或其他名称。 check不检查任何东西,它只是向前移动直到找到第一个元音,因此应该是:

 const firstVowel = (pos = 0) => "aeiou".includes(str.charAt(pos)) ? pos : firstVowel(pos + 1);

现在,最后一行只是第一个元音的一部分(在开头删除了辅音):

 str.substr(/*from*/ firstVowel() /*till end*/)

如果第一个元音直接在开头:

 firstVowel() === 0

它只是追加

 "way"

否则一开始就需要这些辅音:

 str.substr(0, /*to*/ firstVowel())

并附加一个“ y”。

希望下面的代码通过注释进行解释。

 function translatePigLatin(str) { function check(obj) { return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj; } //return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay'); // The above is explained as equivalent to below: if(check(0) === 0){ return str.substr(check(0)).concat('w'+'ay') } return str.substr(check(0)).concat(str.substr(0, check(0))+'ay') } // test here console.log(translatePigLatin("consonant")); // should return "onsonantcay" 

在不确定三元语句的功能时,将三元语句分解为if / else块通常会很有帮助。

 function translatePigLatin(str) { function check(index) { // return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj; // break down ternary into traditional if also changed obj to index to be more descriptive const vowels = ['a','i','u','e','o']; // if the character at the given index exists then check the next character if (vowels.indexOf(str.charAt(index)) === -1) { return check(index + 1) } // otherwide return index (vowel case) return index; } // return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay'); // set base translated word as the first letter in word that is not a vowel. const indexKey = check(0) // get string after index key let substringed = str.substr(indexKey) // get string from beginning until indexkey let appended = str.substr(0, indexKey); // if the index key is the first letter (word starts with vowel) use 'w' if (indexKey === 0) { appended = 'w'; } // return string return `${substringed}${appended}ay`; } // test here const singleConsonant = translatePigLatin("constant"); const doubleConsonant = translatePigLatin("chain"); const vowel = translatePigLatin("analyze") console.log(singleConsonant, doubleConsonant, vowel); 

暂无
暂无

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

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