Brief explanation of each of these JavaScript array methods:
-
reverse()
: This method is used to reverse the order of the elements in an array. It modifies the original array and returns the reversed array. -
push()
: This method is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array. -
sort()
: This method is used to sort the elements of an array in ascending order by default, or based on a provided comparison function. It modifies the original array and returns the sorted array.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
var old_pl = new Array("Cobol", "Fortran", "Algol");
//Reverse
document.write(old_pl.reverse() + "<br>");
//Push New Elements
old_pl.push("Basic", "Asembler", "Simula");
document.write("After Push: " + old_pl + "<br>");
//Sort Elements
old_pl.sort();
document.write("After Sorting: "+ old_pl);
</script>
</body>
</html>
This script creates an array called old_pl
with three elements: "Cobol", "Fortran", and "Algol". Then, three array methods are called on the old_pl
array.
The first method is reverse()
, which reverses the order of the elements in the old_pl
array. The resulting reversed array is output to the webpage using the document.write()
method.
The second method is push()
, which adds three new elements to the end of the old_pl
array: "Basic", "Assembler", and "Simula". The modified array is output to the webpage using the document.write()
method.
Finally, the sort()
method is called on the old_pl
array to sort the elements in alphabetical order. The sorted array is output to the webpage using the document.write()
method.
The resulting output of this script would be:
Algol,Fortran,Cobol
After Push: Algol,Fortran,Cobol,Basic,Assembler,Simula
After Sorting: Algol,Assembler,Basic,Cobol,Fortran,Simula
The first line shows the reversed old_pl
array, with the elements in reverse order. The second line shows the old_pl
array after the push()
method has added the new elements. The third line shows the old_pl
array after the sort()
method has sorted the elements in alphabetical order.
No comments:
Post a Comment