0

I'm running a code similar to the following in a browser:

let str = "hello.\n"
console.log(srt);
for (let i in str) {
    console.log(i);
    console.log(str [i]);
}

I can't figure out why the loop does not stop at the last character? Here is the output:

Hello.

core.js:57 0
core.js:58 H
core.js:57 1
core.js:58 e
core.js:57 2
core.js:58 l
core.js:57 3
core.js:58 l
core.js:57 4
core.js:58 o
core.js:57 5
core.js:58 .
core.js:57 6
core.js:58 

core.js:57 replaceAt
core.js:58 ƒ (index,newChar){return this.substr(0,index)+newChar+this.substr(index+newChar.length);}

I try to reproduce the problem, but it works fine outside my whole application. Of course, the problem comes from my app, but I don't even understand why the loop does not stop at index 6 (last character).

I don't either understand what is the last printed index replaceAt, any idea?

The string length is 7 character as expected.

// Display 7 in the console
console.log (str.length)
Fifi
  • 3,360
  • 2
  • 27
  • 53

1 Answers1

1

Something in your application is polluting your String prototype along the lines of the following:

String.prototype.replaceAt = function (index,newChar){return this.substr(0,index)+newChar+this.substr(index+newChar.length);};

let str = "hello.\n"
console.log(str);
for (let i in str) {
    console.log(i);
    console.log(str [i]);
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • The string comes from a JS array `let test = [ { image: "/dev/images/img0.svg", text: "this is a zero." },...` and I removed all the operations on the string. The string only travels through functions parameters. – Fifi Mar 15 '23 at 10:37
  • 1
    I'm not talking about this specific string. I'm talking about the string *prototype*. – Robby Cornelissen Mar 16 '23 at 01:01