I don’t understand why I’m getting as output just the last item of the loop. I would like to obtain a list with every result, however the code does only return le last item of myArray. Can anyone help?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Distance calculator</title>
<script>
let myArray = [5, 7, 9]
function calcolo(){
for(let i=0; i<myArray.length; i++){
var y = myArray[i];
var risultato = y*y;
document.getElementById('Calcolo').innerHTML = + risultato + "<br>";
}
}
</script>
</head>
<body>
<div id="posizione">
<button onclick="calcolo();"> calcola</button>
</div>
<br>
<div id="Calcolo">
</div>
</body>
</html>
>Solution :
You have to replace =+ with +=.
a =+ b; is equivalent to a = +b; which is just a way of casting b to number, that is, type coercion.
Check now by running this snippet with your code:
let myArray = [5, 7, 9]
function calcolo(){
for(let i=0; i<myArray.length; i++){
var y = myArray[i];
var risultato = y*y;
document.getElementById('Calcolo').innerHTML += risultato + "<br>";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Distance calculator</title>
</head>
<body>
<div id="posizione">
<button onclick="calcolo();"> calcola</button>
</div>
<br>
<div id="Calcolo">
</div>
</body>
</html>