search
HomeWeb Front-endJS TutorialSummary of common JavaScript array operation techniques_javascript skills

The examples in this article summarize common operating techniques for JavaScript arrays. Share it with everyone for your reference. The details are as follows:

Foreword

I believe everyone is used to common array-related operations in jquery or underscore and other libraries, such as $.isArray, _.some, _.find and other methods. This is nothing more than some additional packaging for array operations in native js.
Here we mainly summarize the commonly used APIs for JavaScript array operations. I believe it will be helpful for everyone to solve program problems.

1. Properties
An array in JavaScript is a special object. The index used to represent the offset is a property of the object, and the index may be an integer. However, these numeric indices are converted to string types internally because property names in JavaScript objects must be strings.

2. Operation

1 Determine array type

Copy code The code is as follows:
var array0 = []; // Literal
var array1 = new Array(); // Constructor
// Note: The Array.isArray method is not supported under IE6/7/8
alert(Array.isArray(array0));
// Considering compatibility, you can use
alert(array1 instanceof Array);
// or
alert(Object.prototype.toString.call(array1) === '[object Array]');

2 Arrays and Strings

Very simple: to convert from array to string, use join; to convert from string to array, use split.

Copy code The code is as follows:
// join - convert from array to string, use join
console.log(['Hello', 'World'].join(',')); // Hello,World
// split - convert from string to array, use split
console.log('Hello World'.split(' ')); // ["Hello", "World"]

3 Find elements

I believe that everyone commonly uses the string type indexOf, but few know that the indexOf of an array can also be used to find elements.

Copy code The code is as follows:
// indexOf - find element
console.log(['abc', 'bcd', 'cde'].indexOf('bcd')); // 1

//
var objInArray = [
{
         name: 'king',
Pass: '123'
},
{
          name: 'king1',
Pass: '234'
}
];

console.log(objInArray.indexOf({
name: 'king',
Pass: '123'
})); // -1

var elementOfArray = objInArray[0];
console.log(objInArray.indexOf(elementOfArray)); // 0

As can be seen from the above, for an array containing objects, the indexOf method does not obtain the corresponding search result through in-depth comparison, but only compares the references of the corresponding elements.

4 Array connection

Use concat. Please note that a new array will be generated after using concat.

Copy code The code is as follows:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); // After implementing array concatenation, a new array will be created
console.log(array3);

5 types of list operations

For adding elements, you can use push and unshift respectively, and for removing elements, you can use pop and shift respectively.

Copy code The code is as follows:
// push/pop/shift/unshift
var array = [2, 3, 4, 5];

//Add to the end of the array
array.push(6);
console.log(array); // [2, 3, 4, 5, 6]

//Add to the head of the array
array.unshift(1);
console.log(array); // [1, 2, 3, 4, 5, 6]

//Remove the last element
var elementOfPop = array.pop();
console.log(elementOfPop); // 6
console.log(array); // [1, 2, 3, 4, 5]

//Remove the first element
var elementOfShift = array.shift();
console.log(elementOfShift); // 1
console.log(array); // [2, 3, 4, 5]

6 splice methods

Main two uses:
① Add and delete elements from the middle of the array
② Obtain a new array from the original array

Of course, the two uses are combined in one go. Some scenes focus on the first use, and some focus on the second use.

Add and delete elements from the middle of the array. The splice method adds elements to the array. The following parameters need to be provided
① Starting index (that is, where you want to start adding elements)
② The number of elements to be deleted or the number of elements to be extracted (this parameter is set to 0 when adding elements)
③ Elements you want to add to the array

Copy code The code is as follows:
var nums = [1, 2, 3, 7, 8, 9];
nums.splice(3, 0, 4, 5, 6);
console.log(nums); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Then perform deletion operation or extract new array
var newnums = nums.splice(3, 4);
console.log(nums); // [1, 2, 3, 8, 9]
console.log(newnums); // [4, 5, 6, 7]

7 Sort

Mainly introduce two methods: reverse and sort. Array reversal uses reverse, and the sort method can be used not only for simple sorting, but also for complex sorting.

Copy code The code is as follows:
//Reverse the array
var array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array); // [5, 4, 3, 2, 1]
We first sort the array of string elements
var arrayOfNames = ["David", "Mike", "Cynthia", "Clayton", "Bryan", "Raymond"];
arrayOfNames.sort();
console.log(arrayOfNames); // ["Bryan", "Clayton", "Cynthia", "David", "Mike", "Raymond"]

We sort an array of numeric elements
Copy code The code is as follows:
// If the array elements are of numeric type, the sorting result of the sort() method cannot be Very satisfying
var nums = [3, 1, 2, 100, 4, 200];
nums.sort();
console.log(nums); // [1, 100, 2, 200, 3, 4]

The sort method sorts the elements in lexicographic order, so it assumes that the elements are all of string type, so even if the elements are of numeric type, they are considered to be of string type. At this time, you can pass in a size comparison function when calling the method. When sorting, the sort() method will compare the sizes of the two elements in the array based on this function to determine the order of the entire array.
Copy code The code is as follows:
var compare = function(num1, num2) {
Return num1 > num2;
};
nums.sort(compare);
console.log(nums); // [1, 2, 3, 4, 100, 200]

var objInArray = [
{
         name: 'king',
Pass: '123',
index: 2
},
{
          name: 'king1',
Pass: '234',
index: 1
}
];
// Sort the object elements in the array in ascending order according to index
var compare = function(o1, o2) {
Return o1.index > o2.index;
};
objInArray.sort(compare);
console.log(objInArray[0].index

8 Iterator methods

Mainly includes forEach and every, some and map, filter
I believe everyone knows forEach, and I will mainly introduce the other four methods.
The every method accepts a function that returns a Boolean value and applies the function to each element in the array. This method returns true if the function returns true for all elements.

Copy code The code is as follows:
var nums = [2, 4, 6, 8];
//Iterator method that does not generate a new array
var isEven = function(num) {
Return num % 2 === 0;
};
// Only returns true if they are all even numbers
console.log(nums.every(isEven)); // true

Some methods also accept a function whose return value is a Boolean type. As long as there is an element that causes the function to return true, the method returns true.
var isEven = function(num) {
Return num % 2 === 0;
};
var nums1 = [1, 2, 3, 4];
console.log(nums1.some(isEven)); // true

Both methods map and filter can generate new arrays. The new array returned by map is the result of applying a function to the original elements. Such as:

Copy code The code is as follows:
var up = function(grade) {
Return grade = 5;
}
var grades = [72, 65, 81, 92, 85];
var newGrades = grades.ma

The filter method is very similar to the every method, passing in a function whose return value is a Boolean type. Different from the every() method, when the function is applied to all elements in the array and the result is true, this method does not return true, but returns a new array containing the result of applying the function. elements.
Copy code The code is as follows:
var isEven = function(num) {
Return num % 2 === 0;
};
var isOdd = function(num) {
Return num % 2 !== 0;
};
var nums = [];
for (var i = 0; i nums[i] = i 1;
}
var evens = nums.filter(isEven);
console.log(evens); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
var odds = nums.filter(isOdd);
console.log(odds); // [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

3. Summary

There is also the problem that some of the above methods are not supported by low-level browsers, and other methods need to be used for compatible implementation.

These are common methods that may not be easy for everyone to think of. You may wish to pay more attention to it.

I hope this article will be helpful to everyone’s JavaScript programming design.

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.