【问题标题】:Why won't this iterate?为什么不迭代?
【发布时间】:2020-07-22 06:30:52
【问题描述】:

我正在尝试制作这个 Pig Latin 函数(我 3 周前才开始编码,所以请放轻松),但我不明白为什么我不能得到由 .split(' ') 组成的数组,然后迭代以再次加入。在输出中,我只得到第一个单词。代码如下:

function pigLatin(str) {
  let str1 = str.split(' ')
  for (let i = 0; i < str1.length; i++) {
    if (str1[i].length <= 1) {
      return str1[i]; 
    }
    else {
      let first = str1[i].substring(0,1);
      let word = str1[i].substring(1);
      str = word + first + 'ay';
      return str
    }
  }
}

console.log(pigLatin("This is a test"));

请记住,我正在考虑添加正则表达式和更多其他 if 语句,但我什至无法让它工作。非常感谢任何帮助。

【问题讨论】:

标签: javascript arrays iteration


【解决方案1】:

returning 太早了。您应该将每个单词添加到一个数组中,并且在循环结束时,您应该连接数组中的单词以形成一个您应该返回的新字符串。请参阅我的 cmets,了解我如何更改您的代码:

function pigLatin(str) {
let r = [] // The array to build
let str1 = str.split(' ')
for (let i = 0; i < str1.length; i++) {
  if (str1[i].length <= 1) {
    r.push( str1[i] );  // Add to end of array
  }
  else {
    let first = str1[i].substring(0,1);
    let word = str1[i].substring(1);
    str = word + first + 'ay';
    r.push(str) // Add to end of array
    }
  }
  return r.join(' ') // Join strings in array and return new string
}

console.log(pigLatin("This is a test"));

【讨论】:

  • 啊,谢谢你,我意识到我在开车回家时没有使用推送,但这真的很有帮助。感谢您的回复。
猜你喜欢
  • 2011-02-05
  • 2017-02-09
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多