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

Summary of common JavaScript array operation techniques_javascript skills

WBOY
Release: 2016-05-16 16:31:03
Original
1453 people have browsed it

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.

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template