Home Web Front-end JS Tutorial Summary of common JavaScript array operation techniques_javascript skills

Summary of common JavaScript array operation techniques_javascript skills

May 16, 2016 pm 04:31 PM
javascript Commonly used Skill operate array

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 < objInArray[1].index); // true

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

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

See all articles