Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis0
why is my 0th char not H1 in this while loop?
why is my 0th char not H1 in this loop? https://code.sololearn.com/Wc0y9IdGT5a7/# this script is demonstrating same issue... https://code.sololearn.com/Wx1XWgSIEpIX/#js Why?
1 Resposta
+ 2
Well, you can guess what's happening, isn't it?
What about the output? are all line have same size/weight?... no: when you 'document.write' something, it will be parsed as html ^^
However, the mistake is somewhere else firsly: if you want to print the nth char of a string, you absolutly aren't in the right way! I take you second example:
var i=20;
do {
document.write(i + "<H1 />");
i++;
}
while (i<=25);
What will do this code?
Whit begining 'i' to val 20, we repeat the 'write' command until i <= 25 ( for value of i in range 20 to 25 including ).
Well so the print value at each time of executing will be the result of i + "<H1 />" which is a string: "20<H1 />" on first iteration...
Unfortunaly, '<H1 />' is not valid html... so html parser try to correct it, and display it as it understand ^^ but you get anyway the list of value of 'i' in range 20-25, one per line ( the <h1> auto-corrected tag do breaking lines ).
At no instant you write code to access string characters :P
Well, to do it, you must iterate on a string as this:
var s='<h1 />';
var i=0;
var c=s.length; // we store count of char, to not access it each time the condition below is evaluate
while ( i < c ) // 'less than' is sufficient: index start to 0, so end at ( length - 1 )
{
document.write(s[i]+'<br>'); // access to char string as an array of char, and append a html break line tag to visually see that we write it each by each char
}