search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript arrays and loops_javascript skills

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
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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment