简体   繁体   中英

Why is the for loop with a conditional not iterating all the way to the end of the array?

I am writing a function to change the letters in a string (to camelCase) and the dashes and underscores are used as markers for the end of a word. I want to know why my for loop is stopping before it reaches the end of the array, especially since the conditional code isn't being used.

I've tried console logging my tmp array and it has what I want in it (the '_' or '-'). But the code seems to mess up after the conditional so I'm thinking it has something to do with that.

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)
  }
}

Like pointed out you modify the array as you loop.

Something like a camelCase function might make sense using Array.reduce .

Eg.

 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'));

you may have to be more careful about arr.pop(letter)

The pop() method removes the last element of an array: for every loop you are poping up last item in array..

try removing value @ specified index..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM