Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop return just last item of array

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading