JavaScript array and loop explanation
JavaScript array and loop explanation
This article mainly introduces the JavaScript array and loop details, this article explains how to traverse arrays in a loop, store and access values in order, store and access values in the opposite order, and search in an array. For more information, see
An array is an ordered combination of elements. In JavaScript, Arrays can be created using formal Object Notation or initialized using direct quantitative notation.
The Code is as follows:
Var arrObject = new Array ("val1", "val2"); // acts as an Array of Objects
Var arrLiteral = ["val1", "val2"]; // number of direct Arrays
For developers, there is no difference: An Array method can be called on both the direct volume and the object. For the JavaScript engine, it must be re-interpreted every time the array is accessed directly, especially when it is used in a function.
Use the new operator to create a new Array object:
The Code is as follows:
Var arrObject = new Array ();
You can also create a new array with some values:
The Code is as follows:
Var arrObject = new Array ("val1", "val2 ");
Arrays in JavaScript are indexed from 0, which means that the index of the first element is 0, and the last element is the length of the array minus 1.
1. Traverse arrays cyclically
Problem: it is easy to access all elements of the array.
Solution:
To access an array, the most common method is to use the for Loop:
The Code is as follows:
<Script type = "text/javascript">
Var animals = new Array ("cat", "dog", "whale", "seal ");
Var animalString = "";
For (var I = 0; I <animals. length-1; I ++ ){
AnimalString + = animals [I] + "";
}
Alert (animalString );
</Script>
Discussion:
A for loop can be used to access every element of an array. The array starts from 0, and the array attribute length is used to set the end of the loop.
2. storage and access values in order
Problem: If you want to store values in this way, you can access the values in sequence by storing them;
Solution:
To store and access values in the order of accept values, create a first-in-first-out (FIFO) queue. Use the push method of the JavaScript Array object to add items to the queue and use shift to obtain the items:
The Code is as follows:
<Script type = "text/javascript">
// Create a new array
Var queue = new Array ();
// Press 3 entries
Queue. push ("first ");
Queue. push ("second ");
Queue. push ("third ");
// Obtain two entries
Alert (queue. shift ());
Alert (queue. shift ());
Alert (queue );
</Script>
Discussion:
The Array push method creates a new Array element and adds it to the end of the Array:
The Code is as follows:
Queue. push ("first ");
Each time you press an element, the count of the array element increases.
The Array shift method extracts Array elements from the front of the Array, removes them from the Array, and returns the element:
The Code is as follows:
Var elem = queue. shift ();
For each shift operation element, the array element is automatically subtracted, because shift also modifies the array in addition to the return item.
3. store and access values in reverse order
Problem: to store the value in one way, that is, to access the value in the opposite order, first access the value of the last storage, that is, a stack of the last-in-first-out (LIFO.
Solution:
To store values in reverse order, create a LIFO stack. Use the push method of the JavaScript Array object to add items to the stack, and use the pop method to obtain items:
The Code is as follows:
<Script type = "text/javascript">
// Create a new array
Var stack = new Array ();
// Press 3 entries
Stack. push ("first ");
Stack. push ("second ");
Stack. push ("third ");
// Two entries are displayed.
Alert (stack. pop (); // returns the third entry.
Alert (stack. pop (); // returns the second entry.
Alert (stack); // returns the first entry
</Script>
Discussion:
Stack is also an array, where each newly added element is located at the top of the stack and obtained in the order of first-in-first-out.
The Array push method creates a new element and adds it to the end of the Array:
The Code is as follows:
Stack. push ("first ");
Each time an element is pushed in, the count of the array element increases automatically.
The Array pop method extracts Array elements from the end of the Array, removes them from the Array, and returns the elements:
The Code is as follows:
Var elem = stack. pop ();
Each time an element is displayed, the array element count is automatically reduced, because the array is modified in the pop-up.
4. Search in the array
Problem: You want to search for a specific value in the array. If you find the value, you can obtain the index of the array element.
Solution:
Use the new (ECMAScript 5) Array object Methods indeOf and lastIndexOf:
The Code is as follows:
<Script type = "text/javascript">
Var animals = new Array ("dog", "cat", "seal", "elephant", "lion ");
Alert (animals. indexOf ("elephant"); // print 3
Alert (animals. indexOf ("seal", 2); // print 2
</Script>
Although the browser sometimes supports both indexOf and lastIndexOf, this is just a formula in ECMAScript 5. Both methods accept a search value and compare it with each element in the array. If this value is found, both methods return an index of the array element. If no value is found, return-1. indexOf to return the first element found, and lastIndexOf to return the last element found.
See:
Not all browsers support indexOf and lastindexOf. Solutions for this function:
The Code is as follows:
<Script type = "text/javascript">
If (! Array. prototype. indexOf ){
Array. prototype. indexOf = function (elt/*, from */){
Var len = this. length >>> 0;
Var from = Number (arguments [1]) | 0;
From = (from <0 )? Math. ceil (from): Math. floor (from );
If (from <0 ){
From + = len;
}
For (; from <len; from ++ ){
If (from in this & this [from] === elt ){
Return from;
}
}
Return-1;
}
}
</Script>
5. Apply a function to each numeric Element
Problem: If you want to use a function to check an array value, replace it if the given conditions are met.
Solution:
Use the forEach method of the new ECMAScript 5 Array object to bind a callback function to each Array element:
The Code is as follows:
<Script type = "text/javascript">
Function replaceElement (element, index, array ){
If (element = "AB "){
Array [index] = "**";
}
}
Var charSets = new Array ("AB", "bb", "cd", "AB", "cc", "AB", "dd", "AB ");
// Apply the function to each array element
CharSets. forEach (replaceElement)
Alert (charSets); // print **, bb, cd, **, cc, **, dd ,**
</Script>
Discussion:
The forEach method accepts a parameter, which is a function. This function has three parameters: array elements, element indexes, and arrays.
See:
Most browsers support forEach. However, for browsers that are not supported, you can use the Array. prototype attribute to simulate forEach behavior.
The Code is as follows:
<Script type = "text/javascript">
If (! Array. prototype. forEach ){
Array. prototype. forEach = function (fun/*, thisp */){
Var len = this. length >>> 0;
If (typeof fun! = "Function "){
Throw new TypeError ();
}
Var thisp = arguments [1];
For (var I = 0; I <len; I ++ ){
If (I in this ){
Fun. call (thisp, this [I], I, this );
}
}
};
}
</Script>
6. Create a filtered Array
Problem: You want to filter the values of elements in an array and assign the result to a new array.
Solution:
Use the filter method of the Array object:
The Code is as follows:
<Script type = "text/javascript">
Function removeChars (element, index, array ){
Return element! = "**";
}
Var charSets = new Array ("**", "bb", "cd", "**", "cc", "**", "dd ", "**");
Var newArray = charSets. filter (removeChars );
Alert (newArray); // bb, cd, cc, dd
</Script>
Discussion:
The filter method is a new method added by ECMAScript 5. This method applies a callback function to each array element. The function passed as a parameter to the filter method returns a Boolean value, true or false, Which is returned based on the results of the test array element. The returned value determines whether the array element is added to a new array. If the function returns true, the array element is added. Otherwise, the array element is not added.
See:
Simulation of browsers that do not support the filter method:
The Code is as follows:
<Script type = "text/javascript">
If (! Array. prototype. filter ){
Array. prototype. filter = function (fun/*, thisp */){
Var len = this. length >>> 0;
If (typeof fun! = "Function "){
Throw new TypeError ();
}
Var res = new Array ();
Var thisp = arguments [1];
For (var I = 0; I <len; I ++ ){
If (I in this ){
Var val = this [I]; // put fun and modify this
If (fun. call (thisp, val, I, this )){
Res. push (val );
}
}
}
Return res;
};
}
</Script>
7. Verify the array content
Problem: Make sure that an array meets a certain condition.
Solution:
Use the every method of the Array object to check each element of a given condition.
The Code is as follows:
<Script type = "text/javascript">
Function testValue (element, index, array ){
Var re =/^ [a-zA-Z] + $ /;
Return re. test (element );
}
Var elemSet = new Array ("***", 123, "abc", "-", "AAA ");
Alert (elemSet. every (testValue ));
</Script>
Discussion:
The every and some methods of the Array object are the newest ECMAScript 5 Array methods. The difference is that when the every method is used, the processing will end as long as the function returns a false value, and this method returns false. Some method will continue to test every array element, knowing that the callback function returns true. In this case, no other elements are verified. This method returns true. If the callback function tests all elements and does not return true at any time, some methods return false.
See:
Implementation of browsers that do not support every and some:
The Code is as follows:
<Script type = "text/javascript">
If (! Array. prototype. some ){
Array. prototype. some = function (fun/*, thisp */){
Var I = 0,
Len = this. length >>> 0;
If (typeof fun! = "Function "){
Throw new TypeError ();
}
Var thisp = arguments [1];
For (; I <len; I ++ ){
If (I in this
& Fun. call (thisp, val, I, this )){
Return true
}
}
Return false;
};
}
If (! Array. prototype. every ){
Array. prototype. every = function (fun/*, thisp */){
Var len = this. length >>> 0;
If (typeof fun! = "Function "){
Throw new TypeError ();
}
Var thisp = arguments [1];
For (var I = 0; I <len; I ++ ){
If (I in this
& Fun. call (thisp, val, I, this )){
Return false
}
}
Return true;
};
}
</Script>