首页 > 解决方案 > Js 函数应该返回一个特定的字符串,但行为怪异

问题描述

我知道这应该是一项非常简单的任务,但我正在尝试更多地了解 JS 及其行为方式,这个函数的行为应该是这样的:

例子:

加利福尼亚 => aliforniacay
算法 => algorithmway
schwartz => artzschway

california 和 algorithm 单词按预期工作,但 schwartz 没有,我的输出是:omarigg@omarigg-System:$ node pigLatinExercise.js
chwartzsay
hwartzscaywartzschay
artzschway
<= 我的预期结果
schwartzway

我不明白为什么变量 newPhrase2 在 else 范围内等于“artzschway”,但是当我在 for 范围之外返回相同的变量时,将其值更改为“schwartzway”

我该如何处理这个范围问题?我也知道用正则表达式工具解决这个问题更可行,但我想以这种方式处理这个问题,以了解更多信息。

function translatePigLatin(str) {
  var arrayToAdd = [];

  function cond(index) {
    return (str[index] === 'a' ||
      str[index] === 'e' ||
      str[index] === 'i' ||
      str[index] === 'o' ||
      str[index] === 'u')
  }

  for (var i = 0; i <= str.length + 1; i++) {
    if (cond(i)) {
      //console.log('vowel at first')
      var newPhrase2 = str + 'way'
      break
      //console.log(str)
    } else {
      //console.log('not vowel at first')
      let theWord = str[i];
      arrayToAdd.push(theWord);
      //console.log(arrayToAdd)
      let newPhrase = str.slice(i + 1, str.length + 1)
      //console.log(newPhrase);
      let newPhrase2 = newPhrase + arrayToAdd.join("") + 'ay'
      console.log(newPhrase2);
    }
  }

  //console.log(arrayToAdd.join(""));
  // arrayToAdd.join("");
  // newPhrase = newPhrase + arrayToAdd + 'ay'
  //console.log(newPhrase2)
  return newPhrase2;
}

console.log(translatePigLatin("schwartz"))

标签: javascriptnode.jsvariablesscope

解决方案


请尝试此代码,它应该可以正常工作!


function translatePigLatin(str) {
  let stringToAdd = '';
  let newPhrase2 = '';
  let newPhrase = '';

  function cond(index) {
    return (str[index] === 'a' ||
      str[index] === 'e' ||
      str[index] === 'i' ||
      str[index] === 'o' ||
      str[index] === 'u')
  }
  
  if (cond(0)) {
      newPhrase2 = str + 'way';
      console.log(newPhrase2);
      return newPhrase2;
    }
  else {
    for (let i = 0; i < str.length; i++) {
        
      let theWord = str[i];
      if(!cond(i)) {
        stringToAdd += theWord;
        newPhrase = str.slice(i + 1, str.length + 1);
      }
      else break;
    }
  }
    
  newPhrase2 = newPhrase + stringToAdd + 'ay';
  console.log(newPhrase2);
  return newPhrase2;
}

translatePigLatin("schwrz");

您的代码无法正常工作的原因是您弄乱了条件逻辑。

您应该在不进入循环的情况下检查第一个字母。如果它不是元音,则进入循环并循环直到找到元音。

我认为在那之后它是不言自明的。


推荐阅读