JavaScript arrays and looping _javascript tips

Source: Internet
Author: User
Tags javascript array

An array is an ordered combination of elements. In JavaScript, arrays can be created using formal object notation, or they can be initialized using direct volume notation.

Copy Code code as follows:

var arrobject = new Array ("Val1", "val2"); As an array of objects
var arrliteral = ["Val1", "Val2"]; Array Direct Quantity

For developers, this makes no difference: You can call an array method on both the direct amount and the object. For the JavaScript engine, each time you access the array directly, you must redefine it, especially when using it in a function.

To create a new array object using the new operator:

Copy Code code as follows:

var arrobject = new Array ();

You can also create a new array with some values:
Copy Code code as follows:

var arrobject = new Array ("Val1", "val2");

The array in JavaScript is 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. Iterate through the array

Question: You want to easily access all the elements of an array.

Solution:

The most common way to access an array is to use a For loop:

Copy Code code 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>

Discuss:

A For loop can be used to access each element of an array. The array starts at 0, and the array property length is used to set the end of the loop.

2. Storing and accessing values sequentially

Problem: You want to store values in such a way that you can access them sequentially in the way they are stored;

Solution:

To store and access values in the order in which they are accepted, create a first-in, first-out (FIFO) queue. Using the push method of the JavaScript array object, add an item to the queue and use shift to get the item:

Copy Code code as follows:

<script type= "Text/javascript" >
Create a new array
var queue = new Array ();

Press into 3 entries
Queue.push ("a");
Queue.push ("second");
Queue.push ("third");

Get two entries
Alert (Queue.shift ());
Alert (Queue.shift ());
Alert (queue);
</script>

Discuss:

The array push method creates a new array element and adds it to the end of the array:

Copy Code code as follows:

Queue.push ("a");

Each time an element is pressed, the count of the array element is increased by itself.

The array shift method extracts an array element from the front of the array, deletes it from the array, and returns the element:

Copy Code code as follows:

var elem = Queue.shift ();

For each element of the shift operation, the array element is reduced, because shift, in addition to returning the item, modifies the array.

3. Store and access values in reverse order

Problem: To store values in a way that accesses values in reverse order, first accesses the most recently stored value, which is a LIFO (LIFO) stack.

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, using the Pop method to get the items:

Copy Code code as follows:

<script type= "Text/javascript" >
Create a new array
var stack = new Array ();

Press into 3 entries
Stack.push ("a");
Stack.push ("second");
Stack.push ("third");

Eject two entries
Alert (Stack.pop ()); Returns a third entry
Alert (Stack.pop ()); Returns a second entry
alert (stack); Returns the first entry
</script>


Discuss:

The stack is also an array in which each newly added element is located at the top of the stack and is obtained in the order of LIFO.

The array push method creates a new element and adds it to the tail of the array:

Copy Code code as follows:

Stack.push ("a");

Each time the element is pressed, the count of the array elements will increase itself.

The array pop method extracts an array element from the tail of the array, removes it from the array, and returns the element:

Copy Code code as follows:

var elem = Stack.pop ();

Each time an element is ejected, the array element count is decremented, because the array is also modified by the pop-up.

4, search in the array

Question: To search for a specific value in an array, get the index of the array element if found.

Solution:

Use the new (ECMAScript 5) Array object method indeof and LastIndexOf:

Copy Code code as follows:

<script type= "Text/javascript" >
var animals = new Array ("Dog", "cat", "seal", "Elephant", "lion");
Alert (Animals.indexof ("Elephant")); Print out 3
Alert (Animals.indexof ("Seal", 2)); Print out 2
</script>

Although browsers sometimes support both indexof and LastIndexOf, this is only formalized in the version of ECMAScript 5. Both methods accept a search value, and then compare it to each element in the array. If the value is found, two methods return an index of the array element. If no value is found, return -1.indexof returns the first element found, LastIndexOf returns the last element found.

See:

Not all browsers support indexof and LastIndexOf, and solutions for this function:

Copy Code code 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, this && this[from] = = ELT) {
return from;
}
}

return-1;
}
}
</script>

5. Apply a function to each numeric element

Question: To use a function to check an array value, replace it if the given condition is met.

Solution:

Use the new ECMAScript 5 Array object's Foreach method to bind a callback function for each array element:

Copy Code code 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 a function to each array element
Charsets.foreach (replaceelement)
alert (charsets); Print out **,bb,cd,**,cc,**,dd,**
</script>

Discuss:

The Foreach method takes a single parameter, which is a function. The function itself has 3 parameters: An array element, an element's index, and a group.

See:

foreach is supported by most browsers. However, for browsers that are not supported, you can use the Array.prototype property to simulate a foreach behavior.

Copy Code code 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

Question: You want to filter the value of an element in an array and assign the result to a new array.

Solution:

Use the filter method of the Array object:

Copy Code code 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>

Discuss:

The filter method is a newly added method of ECMAScript 5, which applies a callback function to each array element. A function passed as a parameter to the filter method returns a Boolean value, True or false, based on the result of the test array element. This return value determines whether the array element is added to a new array, and if the function returns True, it will be added, otherwise it will not be added.

See:

For impersonation implementations of browsers that do not support the filter method:

Copy Code code 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]; Place Fun Modified This
if (Fun.call (Thisp, Val, I, this)) {
Res.push (Val);
}
}
}

return res;
};
}
</script>

7, verify the contents of the array

Question: Want to make sure that an array satisfies a condition.

Solution:

Use the Every method of the array object to examine each element of a given condition.

Copy Code code 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>

Discuss:

The Every and some methods of the array object are the newest ECMAScript 5 array method, except that when the Every method is used, the processing ends when the function returns a value of false, and the method returns false. The some method will continue to test each array element, knowing that the callback function returns TRUE. No more elements are validated at this time, and the method returns True. If the callback function tests all elements and does not return the True,some method at any time returns false.

See:

How to implement browsers that do not support every and some:

Copy Code code 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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.