0

The code is experiencing unexpected behavior when clicking the button.

The button click is meant to only output once each character of 'Hello,' vertically. However, the content of the variable text changes on each button click, leading to different characters being displayed each time. https://sololearn.com/compiler-playground/WvtKP922KJH2/?ref=app

4th Jan 2024, 6:35 AM
Dr Melchisedec Bankole
Dr Melchisedec Bankole - avatar
7 Respostas
+ 2
Your button seems to be working correctly the first time when it is pressed. After that, the content of your "text" variable is changed, so it is understandable that subsequent button pushes will create different result. I am not really sure what outcome you are expecting for the second time.
4th Jan 2024, 6:46 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Like I said, the output changes because your text variable changes. The easy solution is resetting the text variable to its original value, at the end of your function after you updated the document. so in line 43 you can insert text = "Hello"; But it is a better approach to not change text at all. You can initially declare it as a constant in line 27, to make sure its value remains the same: const text = "Hello"; and then just use a different variable name for mutating your output in lines 35, 38, 42: let output = ""; and so on. https://www.sololearn.com/compiler-playground/WzDDM4QuQGV7
4th Jan 2024, 7:18 AM
Tibor Santa
Tibor Santa - avatar
+ 1
The link you provided is not opening. Pls fix it.
4th Jan 2024, 7:27 AM
Dr Melchisedec Bankole
Dr Melchisedec Bankole - avatar
+ 1
Dr Melchisedec Bankole move your let text = "Hello" inside the splitString function. // Function to handle the split operation function splitString() { // 1. Create a string variable: let text = "Hello"; // 2. Split the string into an array of individual characters and store it in "myArr": const myArr = text.split(""); // Splits at each character (empty string) . . .
4th Jan 2024, 7:32 AM
Bob_Li
Bob_Li - avatar
+ 1
Dr Melchisedec Bankole I would do it this way(you don't even need the split method): <body> <h1>JavaScript String Methods</h1> <h2>The split().Method</h2> <p id="demo"></p> <button id="btn">Split Text</button> <script> const text = "Hello"; function resetString(){ demo.innerHTML = text; } resetString(); function splitString(){ demo.innerHTML = ""; for(let i=0; i<text.length; i++) demo.innerHTML +=`${text[i]}<br>`; } btn.addEventListener("click", ()=>{ if(demo.innerHTML===text){ splitString(); btn.textContent = "Reset"; }else{ resetString(); btn.textContent = "Split Text"; } }) </script> </body>
4th Jan 2024, 7:59 AM
Bob_Li
Bob_Li - avatar
0
Thanks mentor Tibor Santa. The button click is meant to only output once each character of 'Hello,' vertically. Subsequent clicks should not change the initial output: H e l l o
4th Jan 2024, 6:50 AM
Dr Melchisedec Bankole
Dr Melchisedec Bankole - avatar