For loop in Javascript

Advertisemen

If you are reading this, I believe, you know already what loop is. If you are a PHP developer, you might find some of the behaviours of FOR loop in javascript are different.

First way to use FOR Loop :
This is pretty much same in PHP and other programming languages.

<div id="displayFruits"></div>
<script>
var fruits = ["Mango", "Banana", "Apple", "Pineapple"];
for(var i = 0; i < fruits.length; i++)
{
document.getElementById("displayFruits")
.innerHTML += fruits[i]+'<br>';
}
</script>
Second way to use FOR Loop :

This one is totally different than any other languages.
<div id="displayFruits"></div>
<script>
var fruits = ["Mango", "Banana", "Apple", "Pineapple"];
fruits.forEach(function (fruit)
{
document.getElementById("displayFruits")
.innerHTML += fruit+'<br>';
});
</script>
Third way to use FOR Loop :
This one is little bit different than other languages.
<div id="displayFruits"></div>
<script>
var fruits = ["Mango", "Banana", "Apple", "Pineapple"];
for(var fruit in fruits)
{
document.getElementById("displayFruits")
.innerHTML += fruits[fruit]+'<br>';
}
</script>

Result :
Mango
Banana
Apple
Pineapple

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D