I. Description
When using JavaScript, we sometimes need to manipulate arrays, such as creating arrays, traversing array elements, sorting, etc.
This document will introduce some basic operations of arrays.
II. Create an array
1) The Array object is used to store multiple values in a single variable. The method of creating an array is as follows:
var txt = new Array("I","love","FR");
alert(txt);
The above code will return I,love,FR
2) There are many ways to create an array. You can also create an empty Array and then defined the value of each element:
var txt = new Array();
txt[0] = "I";
txt[1] = "love";
txt[2] = "FR";
alert(txt);
III. Traverse the array elements
Traversing each element of an array can be realized by using a for loop. For example, we have an array named txt:
var txt = new Array("I","love","FR");
for(i=0;i<txt.length;i++)
{alert(txt[i]);}
The code above can display all the array elements.You can change the code in the for loop according to your requirement.
IV. Convert Array to String
The toString() method can convert an array to a string and return the result. For example:
var var txt = new Array("I","love","FR");
var str = txt.toString();
alert(str);
V. Sorting the array
Just call the sort() method of the array to sort its elements.
If no parameters are used when calling this method, the elements in the array will be sorted alphabetically. If we want to sort the elements according to the numeric values, we can first define a function sortNumber(), and then call it in the form of sort(sortNumber) to achieve the goal:
function sortNumber(a, b){
return a - b
}
var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"
document.write(arr.sort(sortNumber))
The output is: 1,5,10,25,40,1000