Wednesday, July 20, 2011

JavaScript Exercises - pop(), shift(), push() and unshift()

pop() and shift() remove and return the last(pop) or the first(shift) element element from a array.

push() and unshift() add a element into the array in the end (push) or in the front (unshift).

example:
JavaScript Exercises - pop(), shift(), push() and unshift()

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Exercise</title>
<script type="text/javascript">

function exercise(){

var stringsource = "A man and a pen";
var stringarray = stringsource.split(" ");


var result = "stringsource = " + stringsource + "\n\n";
result += "stringarray:\n" + stringarray + "\n\n";

result += "pop(): " + stringarray.pop() + "\n" + " - result = " + stringarray + "\n\n";
result += "shift(): " + stringarray.shift() + "\n" + " - result = " + stringarray + "\n\n";

stringarray.push("push");
result += "push(\"push\"): - result = " + stringarray + "\n\n";

stringarray.unshift("unshift");
result += "unshift(\"unshift\"): - result = " + stringarray + "\n\n";


alert(result);
}


function htmlonload(){
exercise();
}
</script>
</head>
<body onload="htmlonload();">
JavaScript Exercise
</body>
</html>


No comments:

Post a Comment