Array methods
<script type="text/javascript">
var parents = ["Jani", "Tove"]; var brothers = ["Stale", "Kai Jim", "Borge"]; var children = ["Cecilie", "Lone"]; var family = parents.concat(brothers, children); document.write(family); </script> The output of the code above will be:
Jani,Tove,Stale,Kai Jim,Borge,Cecilie,Lone
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
var energy = fruits.join(); document.write('the string energy = '+energy); The output of the code above will be:
the string energy =
Banana,Orange,Apple,Mango
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
var lastelement = fruits.pop(); document.write('"' + lastelement + '" from [' + fruits + ']'); The output of the code above will be:
"Mango" from [Banana,Orange,Apple]
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
fruits.push("Kiwi", "Lemon", "Pineapple"); The output of the code above will be:
Banana,Orange,Apple,Mango,Kiwi,Lemon,Pineapple
a new item to an array:
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
fruits.push("Kiwi"); The result of document.write( fruits ) will be:
Banana,Orange,Apple,Mango,Kiwi
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
var firstelement = fruits.shift(); document.write(firstelement + ' is first element and fruits = ' + fruits); The output of the code above will be:
Banana is first element and fruits =
Orange,Apple,Mango
SYNTAX = array.unshift(element1,element2, ..., elementX)
<script type="text/javascript"> Add new items to the beginning of an array:
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
fruits.unshift("Lemon","Pineapple"); The result of document.write(fruits) will be:
Lemon,Pineapple,Banana,Orange,Apple,Mango
<script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write(fruits.slice(0,1) + "<br />"); document.write( fruits.slice(1) + "<br />"); document.write( fruits.slice(-2) + "<br />"); //( 2 last! ) document.write(fruits); </script> The output of the code above will be:
var fruits = ["Banana",
"Orange", "Apple",
"Mango"];
var fruits.reverse(); The result of fruits will be:
Mango,Apple,Orange,Banana
|