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

How does ternary operator work in the function?

你能给我解释一下这个算法中的 return 行吗?

该函数应该接受一个字符串,return 它是 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);