The JavaScript Array reverse means reversing the order of elements in an array. In JavaScript Array Reverse is possible by using reverse()
method. This method reverse an array in place, that means the first element in an array becomes the last element and the last becomes the first.
In JavaScript, by using reverse()
method we can reverse the order of the elements in an array. The reverse()
method is generally called as Array Reverse.
EXAMPLE: Reversing the order of the elements in an array.
<p>Click the below button to reverse the order of element.</p> <input type="button" onclick="myValue()" value="Reverse"/> <p id="myId"></p> <script> function myValue() { var a = ["France", "Egypt", "Darziling", "China", "Bangladesh", "Abudhabi"]; var b = a.reverse(); document.getElementById("myId").innerHTML = b; } </script>
In the above code snippet we have given Id
as "myId
"to the second <p>
element in the HTML code. There is a function myValue() in the<script>
block which is connected to the onclick of the HTML button and array with value "["France", "Egypt", "Darziling", "China", "Bangladesh", "Abudhabi"]" to the variable a
. We need to reverse the order of the elements, for that we are using reverse()
method, which reverses the order of an array. Onclick of the button "Reverse" in the HTML code fires the function myValue() in the <script>
block, at the same time reverse()
method reverses the order of the elements in array and return as output.
OUTPUT
EXAMPLE: Reversing the order of the numbers in an array.
<p>Click the below button to reverse the order of numbers.</p> <input type="button" onclick="myValue()" value="Reverse"/> <p id="myId"></p> <script> function myValue() { var a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var b = a.reverse(); document.getElementById("myId").innerHTML = b; } </script>
Reverse the order of numbers in an array
Onclick of the button "Reverse" in the HTML code fires the function myValue() in the <script>
block, at the same time reverse()
method reverses the order of the numbers in array and return as output.
OUTPUT
Views: 11658 | Post Order: 161