Table of Contents
What is a JavaScript array
Common operations on JavaScript arrays
Creating arrays
Access the array elements
Add array elements
Delete the array element
Find elements
Array sorting
Array reverse
Other uses of JavaScript arrays
Array splicing
Array splitting
Array mapping
Array filtering
Array iteration
Array length
Summary
Home Web Front-end Front-end Q&A javascript array usage

javascript array usage

May 16, 2023 pm 12:04 PM

JavaScript is a scripting language widely used in web front-end development. It allows developers to achieve rich interactive effects in web pages through its concise syntax, flexibility and ease of use. Among them, JavaScript array is a very useful data structure, which can store multiple data and perform various operations. This article takes an in-depth look at the usage of JavaScript arrays and provides some practical tips for beginners and intermediate developers.

What is a JavaScript array

First, let us understand the concept of a JavaScript array. Simply put, an array is a data structure consisting of several elements of any data type, arranged in a certain order, and referenced by a subscript. In an array, each element has its own position, called a subscript or index, which increases from 0.

The following is a simple JavaScript array example, which represents an array containing 5 integers:

var myArray = [10, 20, 30, 40, 50];
Copy after login

In this array:

  • 10 is the first element, its subscript is 0;
  • 20 is the second element, its subscript is 1;
  • 30 is the third element, its subscript is 2;
  • 40 is the fourth element, its subscript is 3;
  • 50 is the fifth element, and its subscript is 4;

When we need to access an element in the array, we can use square brackets[ ] Add the subscript of the element to reference it, such as:

console.log(myArray[2]); // 30
Copy after login

This line of code will output the element with subscript 2 in the array, that is, 30.

Common operations on JavaScript arrays

Next, we will introduce some of the most commonly used operations on JavaScript arrays one by one:

Creating arrays

JavaScript arrays can be Created in two ways. The first method is to use square brackets [] to get an empty array, and then add elements to it one by one:

var myArray = [];
myArray[0] = "apple";
myArray[1] = "orange";
myArray[2] = "banana";
Copy after login

The second method is to directly put the elements in square brackets, in Declare the array in the statement:

var myArray = ["apple", "orange", "banana"];
Copy after login

Access the array elements

You can use square brackets [] plus the subscript of the element to access the elements in the array, or you can use a loop Access all elements at once:

var myArray = [10, 20, 30];
console.log(myArray[0]); // 10

for (var i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}
Copy after login

This code will output all elements in the array, that is:

10
20
30
Copy after login

Add array elements

To add an element at the end of the array, you can use push() method; add an element at the beginning of the array, you can use unshift() method:

var myArray = [10, 20, 30];
myArray.push(40); // 添加元素 40 到数组末尾
myArray.unshift(0); // 添加元素 0 到数组开头
console.log(myArray); // [0, 10, 20, 30, 40]
Copy after login

Delete the array element

At the end of the array To delete an element, you can use the pop() method; to delete an element at the beginning of the array, you can use the shift() method; to delete an element at any position, you can use splice( ) Method:

var myArray = [0, 10, 20, 30, 40];
myArray.pop(); // 删除最后一个元素
myArray.shift(); // 删除第一个元素
myArray.splice(1, 2); // 删除第 2~3 个元素
console.log(myArray); // [20, 30]
Copy after login

Among them, the first parameter of the splice() method is the starting position of deletion, and the second parameter is the number of deletions.

Find elements

You can use the indexOf() method to find whether an array contains an element. This method will return the subscript of the first occurrence of the element, or -1 (if not found):

var myArray = [10, 20, 30, 20, 40];
console.log(myArray.indexOf(20)); // 1
console.log(myArray.indexOf(50)); // -1
Copy after login

Array sorting

You can use the sort() method to sort the elements in the array, default It is arranged in string order. You can pass a comparison function to customize the sorting rules:

var myArray = [40, 10, 30, 20, 50];
myArray.sort();
console.log(myArray); // [10, 20, 30, 40, 50]

myArray.sort(function(a, b) {
  return a - b;
});
console.log(myArray); // [10, 20, 30, 40, 50]
Copy after login

Array reverse

You can use the reverse() method to change the elements in the array Flip:

var myArray = [10, 20, 30, 40, 50];
myArray.reverse();
console.log(myArray); // [50, 40, 30, 20, 10]
Copy after login

Other uses of JavaScript arrays

In addition to the common operations introduced above, there are many other uses of JavaScript arrays.

Array splicing

You can use the concat() method to splice multiple arrays into one array:

var array1 = [10, 20];
var array2 = [30, 40];
var result = array1.concat(array2);
console.log(result); // [10, 20, 30, 40]
Copy after login

Array splitting

You can use the slice() method to extract part of the array and generate a new array:

var myArray = [10, 20, 30, 40, 50];
console.log(myArray.slice(1, 4)); // [20, 30, 40]
Copy after login

Among them, the first parameter of the slice() method is The starting point subscript, the second parameter is the ending point subscript, excluding the element pointed to by the ending point subscript.

Array mapping

You can use the map() method to perform certain processing on each element in the array and return a new array:

var myArray = [10, 20, 30];
var result = myArray.map(function(item) {
  return item * 2; // 将每个元素乘以 2
});
console.log(result); // [20, 40, 60]
Copy after login

Array filtering

You can use the filter() method to filter elements that meet the conditions in the array and return a new array:

var myArray = [10, 20, 30];
var result = myArray.filter(function(item) {
  return item > 15; // 筛选大于 15 的元素
});
console.log(result); // [20, 30]
Copy after login

Array iteration

You can use the forEach() method to perform certain operations on each element in the array without returning any value:

var myArray = [10, 20, 30];
myArray.forEach(function(item) {
  console.log(item); // 输出每个元素
});
Copy after login

Array length

You can use length Attribute to get the length of the array:

var myArray = [10, 20, 30];
console.log(myArray.length); // 3
Copy after login

Summary

Through the introduction of this article, we can understand the basic usage and common operations of JavaScript arrays, so that we can be more flexible and flexible during the development process. Use arrays efficiently. Of course, the functions of JavaScript arrays are far more than this. For advanced developers, there are more advanced techniques and applications. We hope that readers can continue to explore and discover its powerful capabilities in the process of learning and using JavaScript arrays, thereby creating more interesting and practical web page interaction effects.

The above is the detailed content of javascript array usage. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What is useEffect? How do you use it to perform side effects? What is useEffect? How do you use it to perform side effects? Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

How does currying work in JavaScript, and what are its benefits? How does currying work in JavaScript, and what are its benefits? Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work? How does the React reconciliation algorithm work? Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

What is useContext? How do you use it to share state between components? What is useContext? How do you use it to share state between components? Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers? How do you prevent default behavior in event handlers? Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What are the advantages and disadvantages of controlled and uncontrolled components? What are the advantages and disadvantages of controlled and uncontrolled components? Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles