search
HomeWeb Front-endJS TutorialArray Extras in JavaScript

Array Extras in JavaScript

JavaScript arrays are a basic data structure in many programming languages, and JavaScript is no exception. To simplify many details of working with arrays, JavaScript provides a set of features called array extension functions. This article introduces various array extension functions and their uses.

Key Points

  • Array extension functions in JavaScript are functions that simplify many details of working with arrays, improving the readability of the code by replacing complex loops with function calls. They include methods such as forEach(), map(), filter(), every(), some(), reduce(), reduceRight(), indexOf(), lastIndexOf(),
  • and
  • . forEach() The
  • method eliminates the need for loops and array subscript notation by calling a callback function on each element in the array. However, it can cause performance degradation due to calling the function for each element. map() The forEach()filter() function is similar to
  • , but it returns an array containing the values ​​returned by the callback function. The
  • method also returns an array of values, but it is based on the return value of the callback function that should return a boolean value. reduce() The reduceRight()indexOf() method processes each element in the array, computes a single value, while lastIndexOf() works the same way, but starts at the end of the array. The
  • method searches for specific elements in the array, and
also does the same thing, but starts the search from the end of the array.

Background

for

Almost all array operations are performed by traversing each array element one at a time. For example, the following code uses a
var foo = ["a", "b", "c", "d"];

for (var i = 0, len = foo.length; i < len; i++) {
  console.log(foo[i]);
}
loop to record all elements of an array to the debug console.

First and most importantly, you should understand that the previous example is completely valid JavaScript code. However, if you have several complex loops, tracking variables can become tedious. Array extension functions allow us to replace the entire loop with function calls, which can usually improve the readability of the code. Now, let's take a look at various array extension functions.

forEach()

forEach() Like many array extension functions, the method is a forEach() higher-order functionforEach()—a function that receives another function as a parameter.

Instead of traversing array elements, the callback function is called on each element in sequence. The callback function accepts three parameters—the current array element, the array index, and the array itself. In the following code, the original example has been rewritten to use the method.
var foo = ["a", "b", "c", "d"];

for (var i = 0, len = foo.length; i < len; i++) {
  console.log(foo[i]);
}

Note that using forEach() eliminates the need for loop and array subscript notation. Additionally, since JavaScript uses function-level scopes, the forEach() callback function provides a new scope that allows reuse of variable names. The only downside is the performance loss incurred by calling the function for each element in the array. Fortunately, this loss is often negligible. Also note that you can pass an optional parameter to forEach() after the callback function. If present, the second parameter defines the this value used in the callback function.

map()

The

map() function is almost the same as forEach(). The only difference is that map() returns an array containing the values ​​returned by the callback function. For example, the following code uses map() to calculate the square root of each item in the input array. Then return the result as an array and display it. Also note that array extension functions are compatible with built-in JavaScript functions such as Math.sqrt().

["a", "b", "c", "d"].forEach(function(element, index, array) {
  console.log(element);
});

filter()

Like forEach() and map(), the filter() method accepts a callback function and optional this value. And, like map(), filter() returns an array of values ​​based on the return value of the callback function. The difference is that the filter() callback function should return a boolean value. If the return value is true, add the array element to the result array. For example, the following code removes any element in the original array that does not start with the letter x. In this example, the regular expression (passed as a this value) will be tested for each array element.

var sqrts = [1, 4, 9, 16, 25].map(Math.sqrt);

console.log(sqrts);
// 显示 "[1, 2, 3, 4, 5]"

every() and some()

The

every() and some() functions also run callback functions on each array element. If each callback function returns true, every() returns true, otherwise false. Similarly, if at least one callback function returns true, some() returns true. In the following example, every() and some() are used to test whether the array element is less than five. In this case, every() returns false because the last element is equal to five. However, some() returns true because at least one element is less than five. Note that the index and array parameters exist, but have been omitted from the callback function, as they are not needed in this example.

["x", "abc", "x1", "xyz"].filter(RegExp.prototype.test, /^x/);

reduce() and reduceRight()

The

reduce() method processes each element in the array (starting from the beginning) and calculates a single value. reduce()Prefer the callback function and optional initial value as parameters. If no initial value exists, the first array element is used. reduce() The callback function is different from the other callback functions we have seen so far in that it accepts four parameters—the previous value, the current value, the index, and the array. A common example of reduce operations is to add all values ​​of an array. The following example does exactly this. When the callback function is called for the first time, previous is equal to 1 and current is equal to 2. In subsequent calls, the sum accumulates to the final value 15.

var foo = ["a", "b", "c", "d"];

for (var i = 0, len = foo.length; i < len; i++) {
  console.log(foo[i]);
}
The

reduceRight() method works the same way as reduce(), except that the process starts from the end of the array and moves toward the beginning.

indexOf() and lastIndexOf()

The

indexOf() method searches for a specific element in the array and returns the index of the first match. If no match is found, indexOf() returns -1. indexOf()Please the element to be searched for as its first parameter. The second optional parameter specifies the starting index of the search. For example, the following code looks for the first two occurrences of the letter z in the array. To find the second appearance, we just need to find the first appearance and start searching again from after it.

["a", "b", "c", "d"].forEach(function(element, index, array) {
  console.log(element);
});
The

lastIndexOf() method works exactly the same way, except that it starts searching from the end of the array.

Conclusion

Use array extension functions to write concise and clear code. Unfortunately, some older browsers do not support these methods. However, you can detect these methods by checking the Array.prototype object (i.e. Array.prototype.forEach). If a method is missing, you can easily provide your own implementation.

(The FAQ part should be added here, the content is the same as the FAQ part in the input text, but corresponding pseudo-original modifications are required, such as adjusting the order of the statement, replacing synonyms, etc.)

The above is the detailed content of Array Extras in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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