0

Currently learning Javascript, and was doing an exercise with functions and objects. Why did this work:

decipher = (str, obj) => {
  str = str.split("")
  let keys = Object.keys(obj)
  for(let i=0; i<str.length; i++) {
    for(let j=0; j<keys.length; j++) {
      if(str[i] === keys[j]) {
       str[i] = obj[keys[j]]      
      }
    }
  }
  return str.join("")
}

But this didn't?:

  decipher = (str, obj) => {
  str = str.split("")
  let keys = Object.keys(obj)
  for(let i of str) {
    for(let j of keys) {
      if(str[i] === keys[j]) {
       str[i] = obj[keys[j]]      
      }
    }
  }
  return str.join("")
}
Koervege
  • 11
  • 1
  • 4
    Because `for..of` is looping the values already, not indexes, so `i` and `j` aren't indexes, but the values – Calvin Nunes Nov 30 '20 at 13:54
  • 2
    Try to log (or inspect at a breakpoint) the value of `i` and `j` and it'll become obvious. – Bergi Nov 30 '20 at 13:54
  • Have a closer look at [the structure of such loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of). – isherwood Nov 30 '20 at 13:55

0 Answers0