英文:
Iterate through string return index `replaceAt` in JavaScript
问题
以下是您要翻译的内容:
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 characters as expected.
// Display 7 in the console
console.log(str.length)
英文:
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)
答案1
得分: 1
在你的应用程序中,有一些东西正在污染你的 String
原型,类似以下方式:
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]);
}
英文:
Something in your application is polluting your String
prototype along the lines of the following:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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]);
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论