I am trying to make a page that shows the conversion from 1 to 10 dollars, dollar for dollar and that is printed using a while loop but inside a table, but so far I have not been successful. The code I created goes something like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>TablaDolar</title>
</head>
<body>
<table width="200" border="1">
<tbody>
<tr>
<td>Dolares</td>
<td>Monto</td>
</tr>
</tbody>
</table>
<script>
var monto = 0;
var dolar = 17,10;
var a = "";
var vueltas = 0;
while(vueltas < 10){
a = "<table width="200" border="1">"
+ "<tbody>"
+ "<tr>"
+ "<td>" + dolar + "</td>"
+ "<td>" + monto + "</td>"
+ "</tr>"
+ "</tbody>"
+ "</table>";
document.write(a);
vueltas ++;
dolar +;
monto ++;
}
Amount indicates the amount of dollars that are being converted dollar indicates the value of the dollar in pesos
Cheers!!
You have several errors in your code, to begin with
17,10
you must change it to17.10
.You also have a typo on
dolar +;
, that throws an error.If you want to use double quotes
"
inside a string you have to escape them in this way\"
or use single quotes to encapsulate it, there are several options.And finally, as Elberth Agreda said, the header of the table must go outside the while.
The code is more or less so that it would be the solution to the question you asked:
There are several bugs found in your code.
17,10
: erroneous declaration of a decimal, considers the point (.
) as a decimal separatordolar +;
: misuse of the incrementer, you should consideri++;
To solve your problem, it would be to build the body of your table and then assign it to the element
tbody
, for which I put the idcontenedor
and through the methoddocumento.getElementById()
I look for the container and assigninnerHTML
the body of your table to its property.References:
Another way is:
Sometimes the
+=
can affect performance, for example, in the tenth iteration it would be something like this:In other words, the nine rows are equal to the 9 rows plus another, which in reality, thanks to JS , is not such a problem, but it is not like that when there are many iterations.
On the other hand when using
push()
you don't have to work with all the previous elements, only with the last one.But in reality for your example you can use the one that suits you best because there is really not much problem with this performance.
The table header should be outside the while like this: