-1

The following is producing unicode, when it should be producing string?

let str = "hello";

let string = []
for(let s in str){
  string.push(str.codePointAt(s))
}
console.log(string) // ASCII

let back = []
for(let s in string){
  back.push(String.fromCharCode(s))
}
console.log(back) // unicode??
Andy
  • 61,948
  • 13
  • 68
  • 95
Dshiz
  • 3,099
  • 3
  • 26
  • 53
  • A `for ... in` loop iterates through the **keys** of an object. Your loop is iterating through the character indexes of the string. – Pointy Jul 05 '22 at 17:04
  • Most Likely this is the answer you are looking for. https://stackoverflow.com/questions/36527642/difference-between-codepointat-and-charcodeat – samaksh shrivastava Jul 05 '22 at 17:05
  • Also note that the argument to `.fromCharCode()` is the actual character code you want. You're just passing the index. – Pointy Jul 05 '22 at 17:05
  • @samakshshrivastava I doubt that. The code in this question simply does not make sense. – Pointy Jul 05 '22 at 17:06
  • https://stackoverflow.com/questions/36527642/difference-between-codepointat-and-charcodeat – samaksh shrivastava Jul 05 '22 at 17:07

1 Answers1

2

for (let s in string) iterates over the indices of each element. You're converting the numbers 0, 1, 2, ... to characters and pushing them into a string.

This is evident if you either add a simple console.log(s) to your loop, or if you examine the output, where each element is clearly sequential starting from 0:

['\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\b']
user229044
  • 232,980
  • 40
  • 330
  • 338