


Summary 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
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.
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.
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.
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.
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
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.
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
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.
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.
//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:
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.
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.

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 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.

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.

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.

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 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...

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...

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.