Home Web Front-end JS Tutorial Detailed explanation of JavaScript arrays and loops_javascript skills

Detailed explanation of JavaScript arrays and loops_javascript skills

May 16, 2016 pm 04:02 PM
javascript cycle 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 literal notation.

Copy code The code is as follows:

var arrObject = new Array("val1", "val2"); // Array as object
var arrLiteral = ["val1", "val2"]; // Array literal

For developers, there is no difference: an Array method can be called on both literals and objects. For the JavaScript engine, an array literal must be reinterpreted every time it is accessed, especially when used within a function.

Use the new operator to create a new Array object:

Copy code The code is as follows:

var arrObject = new Array();

You can also create a new array with certain values:
Copy code 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. Loop through the array

Problem: Want to easily access all elements of an array.

Solution:

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

Copy code The code is as follows:


Discussion:

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

2. Store and access values ​​in order

Problem: Want to store values ​​in such a way that they can be accessed sequentially the way they are stored;

Solution:

To store and access values ​​in the order they are received, 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 get the items:

Copy code The code is as follows:


Discussion:

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

Copy code The code is as follows:

queue.push("first");

Each time an element is pushed, the count of array elements is incremented.

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 The code is as follows:

var elem = queue.shift();

For each element of the shift operation, the array element will be decremented, because shift not only returns the item, but also modifies the array.

3. Store and access values ​​in reverse order

Problem: I want to store values ​​in a way that accesses the values ​​in reverse order, accessing the most recently stored value first, which is a last-in-first-out (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, and the pop method to get items:

Copy code The code is as follows:



Discussion:

The stack is also an array, where each newly added element is at the top of the stack and is obtained in last-in-first-out order.

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

Copy code The code is as follows:

stack.push("first");

Each time an element is pushed, the array element count is incremented.

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 The code is as follows:

var elem = stack.pop();

Every time an element is popped, the array element count will be decremented, because popping also modifies the array.

4. Search in the array

Question: I want to search for a specific value in an array and, if found, get the index of the array element.

Solution:

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

Copy code The code is as follows:


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

See:

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

Copy code The code is as follows:


 5、对每个数字元素应用一个函数

  问题:想要使用一个函数来检查一个数组值,如果满足给定的条件,就替换它。

  解决方案:

  使用新的ECMAScript 5 Array对象的forEach方法,来针对每个数组元素都绑定一个回调函数:

复制代码 代码如下:


讨论:

  forEach方法接受一个参数,这个参数是个函数。该函数自身有3个参数:数组元素,元素的索引和数组。

  参见:

  大多数浏览器都支持forEach。然而,对于那些不支持的浏览器,可以使用Array.prototype属性来模拟forEach行为。

复制代码 代码如下:


6. Create a filtered array

Question: I want to filter the values ​​of elements in an array and assign the results to a new array.

Solution:

Use the filter method of the Array object:

Copy code The code is as follows:


Discussion:

The filter method is a newly added method in ECMAScript 5, which 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, based on the result of testing the array element. This return value determines whether the array element is added to a new array. If the function returns true, it will be added; otherwise, it will not be added.

See:

For simulation implementation of browsers that do not support the filter method:

Copy code The code is as follows:


7. Verify array content

Problem: Want to ensure that an array meets a certain condition.

Solution:

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

Copy code The code is as follows:



Discussion:

The every and some methods of the Array object are both the latest ECMAScript 5 Array methods. The difference is that when using the every method, as long as the function returns a false value, the processing will end and the method returns false. The some method will continue to test each array element until the callback function returns true. At this time, other elements are no longer verified, and this method returns true. If the callback function tests all elements and does not return true at any time, some method returns false.

See:

Implementation method for browsers that do not support every and some:

Copy code The code is as follows:


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

See all articles