I'm just getting started with JavaScript and I'm on the topic of arrays.
Entering the elements of the array through the inputs I must obtain the maximum element and its position.
This what I have tried:
function Calculate() {
var array1 = document.form.elements["array"];
var max = 0;
for (i = 0; i < array1.length; i++) {
if (array1[i].value == null) {
array1[i].value = 0;
}
document.write(array1[i].value + " ");
}
for (i = 0; i < array1.length; i++) {
if (max < array1[i].value) {
max = array1[i].value;
}
}
document.write("<br>El máximo elemento es: " + max);
}
<div>
<form name="form" method="post">
<table>
<tr>
<th>Escribe los elementos del arreglo:</th>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
<td><input type="text" size="2" name="array" /></td>
</tr>
<tr>
<td colspan="11"><input type="button" value="Calcular" onclick="Calculate()" /></td>
</tr>
</table>
</form>
</div>
When I enter a two-digit number onwards, it does not take it into account and calculates the maximum only of the one-digit numbers, that is, from 1 to 9.
I would also like to know how I can fill the empty input positions with zeros when printing the array. And how can I print the results on the same page since when I click it cleans and then prints the results.
the routine evaluates alphabetically and must do it numerically so that it can give the expected result, in the following example I show you how to convert an alphanumeric string
String
to an integerInteger
as well as how to print the result without deleting the page.Example: