The examples in this article describe the usage of Array objects in JavaScript. Share it with everyone for your reference, the details are as follows:
Array array object has many commonly used methods and attributes, which are summarized as follows:
1. The length attribute gets the number of elements in the array.
2. The concat() method connects two arrays. Concatenate two arrays. An example is as follows:
var names= new Array('Jack','Tom','Jim'); var ages= new Array(12,32,44); var concatArray; concatArray=names.concat(ages);
The concatArray here is a new array that combines the name array and the age array.
3. The slice() method obtains some array elements in the array.
Generally there are two parameters, the first represents the starting position, and the second represents the ending position (similar to substring). It is worth noting that the intercepted array element is located before the second parameter position. In other words, if the second parameter is 4, it means intercepting before the fourth array element.
4. The join() method converts the array into a string. This method is a javascript method and is often used in jQuery. The example is as follows:
var myShopping=new Array("eggs","apple","milk"); var myShoppingList = myShopping.join("<br>"); document.write(myShoppingList);
The myShoppingList here becomes a string, the content is "eggs
apple
milk";
5. The sort() method sorts the elements in the array. They are arranged in alphabetical order, from smallest to largest.
6. The reverse() method flips the elements in the array and turns them around.
If you combine the sort() method with the reverse() method, you can achieve the effect of sorting in reverse order.
That is, sort first and then turn over, so as to achieve the effect of reverse order.
The following is a small comprehensive example:
<script type='text/javascript'> var myShopping = new Array("Eggs","Milk","Potatoes","Banana","Cereal"); var ord = parseInt(prompt("Enter 1 for alphabetical order,and -1 for reverse order",1)); switch(ord) { case 1: myShopping.sort(); myShopping = myShopping.join("<br>"); document.write(myShopping); break; case -1: myShopping.sort(); myShopping.reverse(); myShopping = myShopping.join("<br>"); document.write(myShopping); break; default: document.write("That not a valid input."); break; } </script>
This small example is a small example of using the sorting method, flipping method and join method in the array object. If the input is 1, it will be sorted in order and output. If it is -1, it will be sorted in reverse order and output.