stuart-d2
3/7/2016 - 9:58 PM

Arrays JScript

Arrays JScript


//1.  Simple array and test
// isAarray method will help you tell if it is actually an array.typeof only returns 'object'  
<!DOCTYPE html>
<html>
<body>

<p>The new ECMASCRIPT 5 method isArray returns true when used on an array.</p>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = Array.isArray(fruits);
</script>

</body>
</html>

//2.  getting the length of an array

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
</script>

//3.  getting the last element in an array

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length-1;
</script>

//4. Adding to an array with PUSH

<!DOCTYPE html>
<html>
<body>

<p>The push method appends a new element to an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
    fruits.push("Lemon")
    document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>