代码之家  ›  专栏  ›  技术社区  ›  PineNuts0

JavaScript:Write函数,在短语上执行Pig拉丁语;循环出现奇怪的输出

  •  0
  • PineNuts0  · 技术社区  · 7 年前

    我试着写一个不懂拉丁语的代码。两条主要规则如下:

    • 规则2:如果一个单词以辅音开头,把辅音移到单词的末尾。最后在单词的末尾加上一个“是”音。

    const pigify = (str) => {
      let sentSplit = str.split(' ')
      let newArray = [];
    
      for (let i = 0; i < sentSplit.length; i++) {
        let element = sentSplit[i]
        console.log(element)
        // counts 'qu' as a consonant even when it's preceded by a consonant
        if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) && (element.slice(1, 3) === 'qu')) {
          newArray.push(`${element.slice(3)}${element.slice(0,3)}ay`)
        }
    
        // translates a word beginning with three consonants 
        // counts 'sch' as a single phoneme
        else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) &&
          !['a', 'e', 'i', 'o', 'u'].includes(element[1]) &&
          !['a', 'e', 'i', 'o', 'u'].includes(element[2]) ||
          (element.slice(0, 3) === 'sch')
        ) {
          newArray.push(`${element.slice(3)}${element.slice(0,3)}ay`)
        }
    
        // translates a word beginning with two consonants
        // counts 'qu' as a single phoneme
        else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0]) &&
          !['a', 'e', 'i', 'o', 'u'].includes(element[1]) ||
          (element.slice(0, 2) === 'qu')
        ) {
          newArray.push(`${str.slice(2)}${str.slice(0,2)}ay`)
        }
    
        // translates a word beginning with a consonant
        else if (!['a', 'e', 'i', 'o', 'u'].includes(element[0])) {
          newArray.push(`${str.slice(1)}${str[0]}ay`)
        }
    
        // translates a word beginning with a vowel
        else if (['a', 'e', 'i', 'o', 'u'].includes(element[0])) {
          newArray.push(`${element}ay`)
        }
      }
      return newArray.join('')
    }
    
    
    const pigLatinString = pigify('the quick brown fox');
    console.log(pigLatinString);

    ethay ickquay ownbray oxfay
    

    但是我的代码返回:

    'e quick brown foxthaye quick brown foxthaye quick brown foxthayhe quick brown foxtay'
    

    我做错什么了?

    0 回复  |  直到 7 年前
        1
  •  -1
  •   JohnSnow    7 年前

    不包括边缘情况:

    考虑将不同的“任务”分解为不同的“函数”,以便于可读性和调试。

      const startsWithVowel = letter => {
        const vowels = ['a', 'e', 'i', 'o', 'u'];
        if (vowels.includes(letter)) return true;
      };
    
      const turnPigLatin = str => {
        const firstLetter = str.charAt(0);
        if (startsWithVowel(firstLetter)) {
          return str + 'yay';
        } else {
          return str.substr(1) + str.charAt(0) + 'ay';
        }
      };
    
      const pigify = sentence => {
        const words = sentence.split(' ');
        return words.map(word => turnPigLatin(word)).join(' ');
      };
    
      console.log(pigify('The quick brown fox'));
    推荐文章