【问题标题】:Why is the for loop with a conditional not iterating all the way to the end of the array?为什么带有条件的 for 循环不会一直迭代到数组的末尾?
【发布时间】:2019-10-23 14:23:08
【问题描述】:

我正在编写一个函数来更改字符串中的字母(转换为驼峰式),并且破折号和下划线用作单词结尾的标记。我想知道为什么我的 for 循环在到达数组末尾之前就停止了,特别是因为没有使用条件代码。

我已尝试在控制台记录我的 tmp 数组,它包含我想要的内容(“_”或“-”)。但是在条件之后代码似乎搞砸了,所以我认为它与此有关。

for (let letter of arr) {
  arr.pop(letter)
  if (letter === '-' || letter === '_') {
    let tmp = []
    tmp.push(letter)
    console.log(tmp)
  } else {
    camelArr.push(letter)
    console.log(camelArr)
  }
}

【问题讨论】:

  • arr.pop() - 在遍历数组时,您正在从数组中删除项目。
  • pop() 删除项目,因此长度减少。如果您使用其他方法删除不同的项目,也会出现这种情况。你不需要pop()/push()
  • 您不应该在使用循环对其进行迭代时修改集合,而应使用filtermap 等函数
  • arr.pop(letter) 没有意义
  • 谢谢你说得有道理!

标签: javascript arrays loops if-statement


【解决方案1】:

就像指出的那样,您在循环时会修改数组。

使用 Array.reduce 可能会产生类似 camelCase 的函数。

例如。

const camelCase = str =>
  [...str].reduce((a, v) => {
      if (['_', '-'].includes(v)) a.firstLet = true;
      else {
        a.str += a.firstLet ? v.toUpperCase() : v.toLowerCase()
        a.firstLet = false;
      }
      return a;
    }, {str: '', firstLet: false}).str;
  
console.log(camelCase('this_is-a-Test'));
console.log(camelCase('one-two-three-four'));

【讨论】:

    【解决方案2】:

    您可能需要更加小心 arr.pop(字母)

    pop() 方法删除数组的最后一个元素 :对于每个循环,您都会弹出数组中的最后一项..

    尝试删除@指定索引的值..

    【讨论】:

    • 这不是一个真正的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2015-03-31
    • 2017-10-13
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多