JavaScript array and loop details

  • 2020-06-01 08:17:58
  • OfStack

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


var arrObject = new Array("val1", "val2"); // As an array of objects
var arrLiteral = ["val1", "val2"]; // Array direct quantity

For developers, it makes no difference: one Array method can be called on both direct quantities and objects. For the JavaScript engine, it is necessary to reinterpret the array every time it is accessed, especially when it is used in a function.

Create a new Array object using the new operator:


var arrObject = new Array();

You can also create a new array with some values:

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. Loop through groups

Problem: you want to easily access all the elements of an array.

Solutions:

To access an array, the most common method is to use the for loop:


<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:

The 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.

Store and access values in order

Problem: if you want to store values in such a way, you can access the values in the order in which they are stored.

Solutions:

To store and access values in the order they are received, create a first in first out (FIFO) queue. Using the push method of the JavaScript Array object, add items to the queue, and get items with shift:


<script type="text/javascript">
    // Create a new array
    var queue = new Array();     // Push the 3 An item
    queue.push("first");
    queue.push("second");
    queue.push("third");     // Get 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:


queue.push("first");

If you press in one element at a time, the count of the array elements increases.

The Array shift method extracts the array element from the front of the array, removes it from the array, and returns the element:


var elem = queue.shift();

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

Store and access values in reverse order

Problem: you want to store the value in 1 way, i.e. access the value in reverse order, access the most recently stored value first, i.e., 1 last in, first out (LIFO) stack.

Solutions:

To store the values in reverse order, create an LIFO stack. Use the push method of the JavaScript Array object to add items to the stack, and the pop method to get items:


<script type="text/javascript">
    // Create a new array
    var stack = new Array();     // Push the 3 An item
    stack.push("first");
    stack.push("second");
    stack.push("third");     // Two items pop up
    alert(stack.pop()); // Returns the first 3 An item
    alert(stack.pop()); // Returns the first 2 An item
    alert(stack); // Returns the first 1 An item
</script>

Discussion:

The stack is also an array, with each newly added element at the top of the stack and retrieved in lifo order.

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


stack.push("first");

Each time you press in an element, the count of the array element increases.

The Array pop method extracts the array element from the end of the array, removes it from the array, and returns the element:


var elem = stack.pop();

Each time an element is popped up, the array element count is subtracted because the popup also modifies the array.

4. Search the array

Problem: if you want to search an array for a specific value, if you find it, get the index of the array element.

Solutions:

Using the new (ECMAScript 5) Array object methods indeOf and lastIndexOf:


<script type="text/javascript">
    var animals = new Array("dog", "cat", "seal", "elephant", "lion");
    alert(animals.indexOf("elephant")); // Print out the 3
    alert(animals.indexOf("seal", 2)); // Print out the 2
</script>

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

See also:

Not all browsers support indexOf and lastindexOf. The solution for this 1 function is:


<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 1 function to each number element

Problem: you want to use a function to check the value of an array and replace it if the given conditions are met.

Solutions:

Use the forEach method of the new ECMAScript 5 Array object to bind 1 callback function for each array element:


<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 out the **,bb,cd,**,cc,**,dd,**
</script>

Discussion:

The forEach method takes one parameter, which is a function. The function itself takes three arguments: the array element, the index of the element, and the array.

See also:

Most browsers support forEach. However, for browsers that do not support Array.prototype, you can use the Array.prototype property to simulate forEach behavior.


<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 value of an element in an array and assign the result to a new array.

Solutions:

Using the filter method of the Array object:


<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 addition to ECMAScript 5 that applies 1 callback function to each array element. The function passed to the filter method as an argument returns a Boolean, true or false, based on the results of the test array elements. This return value determines whether the array element will be added to a new array. If the function returns true, it will be added. Otherwise, it will not be added.

See also:

Mock implementation for browsers that do not support the filter method:


<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 the fun To modify the this
                    if (fun.call(thisp, val, i, this)) {
                        res.push(val);
                    }
                }
            }             return res;
        };
    }
</script>

7. Verify the contents of the array

Problem: you want to make sure that 1 array satisfies a certain condition.

Solutions:

Use the every method of the Array object to examine each element of a given condition.


<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 both the latest ECMAScript 5 Array methods. The difference is that when the every method is used, as long as the function returns an false value, the processing ends and the method returns false. The some method continues to test each array element until the callback returns true. Instead of validating the other elements, this method returns true. If the callback function tests all the elements and does not return true at any time, the some method returns false.

See also:

For browsers that do not support every and some:


<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 articles: