Home  >  Article  >  Web Front-end  >  How to reverse element position in javascript

How to reverse element position in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-08-10 14:42:041977browse

In the previous article, we learned about the method of determining whether an object is an array. Please see "Teach you a trick to determine whether JavaScript is an array". This time we will learn about the method of reversing the position of elements. You can refer to it if necessary.

We can sometimes see that the elements that are put into the array are output backwards. Do you know what is going on? If you don’t know, it doesn’t matter, we will come back to introduce it today. If you know it, then treat it as a review. Now let’s introduce it.

First let’s look at a small example.

<script>
var arr = new Array(3); 
arr[0] = "one";
arr[1] = "two";
arr[2] = "three";
console.log(arr);
console.log(arr.reverse());
console.log(arr);
</script>

The result of this small example is

How to reverse element position in javascript

#Let’s take a look at the result. The first result is very normal, that is There is no problem with what we defined. The second result is starting to be a bit interesting. It is output in reverse. The third result is also very interesting. I originally thought that it would be output as the original array, but it is not. It seems that there is something to this. ah.

In this result, we reverse the elements in the array "["one", "two", "three"]" to "["three", "two ", "one"]" is output. It seems that there is really a way to reverse the position of elements in javascript.

Then we need to learn this method carefully.

The name of this method is called reverse. reverse()The method is used to reverse the order of elements in the array.

Let’s look at the above example again. When we output the array arr for the first time, it is output according to our definition. Then when we use the reverse() method and then output the array arr, it will be output in the order of the elements after we reverse the array.

So we can draw a conclusion:

This method will change the original array without creating a new array.

Now let’s learn the syntax format of this method and deepen our impression.

数组对象.reverse()

That’s all. If you need it, you can read: javascript advanced tutorial

The above is the detailed content of How to reverse element position in javascript. 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