Home  >  Article  >  Web Front-end  >  How to reverse output array elements in JavaScript? (code example)

How to reverse output array elements in JavaScript? (code example)

青灯夜游
青灯夜游Original
2019-01-16 15:34:378084browse

In JavaScript, you can output array elements in reverse order by using a for loop, or use the reverse() method to output array elements in reverse order. Let’s take you through these two methods in detail, I hope it will be helpful to you. [Recommended related video tutorials: JavaScript Tutorial]

How to reverse output array elements in JavaScript? (code example)

##1. Use a for loop to output array elements in reverse order

Let’s take a look at how to use a for loop to output array elements in reverse order through a simple code example.

<script type="text/javascript">
function fun() {
var arr = [34,"a",567,"haha"];
console.log("原数组为:");
console.log(arr);
console.log("反向输出:");
for(var i = arr.length - 1; i >= 0; i--) {
var temp = arr[i];
console.log(temp);
}
}
fun();//调用myreverse()函数
</script>

Output:

How to reverse output array elements in JavaScript? (code example)

Explanation: Because the subscript of the array starts from 0, use arr.length - 1 To get the subscript of the last element of the array; use i-- to decrement the subscript until the subscript is 0.

2. Use the reverse() method

The reverse() method is used to reverse the order of elements in the array. Make the first element of the array the last element and vice versa.

Note: This method will change the original array but not create a new array.

Example: Use reverse() to reverse the order of the elements in the array and output the elements of the array.

<script type="text/javascript">
function fun() {
var arr = [34,"a",567,"haha"];
console.log("原数组为:");
console.log(arr);
console.log("反向输出:");
var new_arr = arr.reverse(); 
console.log(new_arr);
}
fun();//调用myreverse()函数
</script>

Output:

How to reverse output array elements in JavaScript? (code example)

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to reverse output array elements in JavaScript? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn