This example summarizes common operating techniques for JavaScript arrays. Share it for your reference. The details are as follows:
Preface
I believe everyone is used to using array-related operations commonly used in class libraries such as jquery or underscore, such as $.isArray, _.some, _.find and other methods. Here is nothing more than a little more wrappers for native js array operations.
Here we will mainly summarize the common APIs for JavaScript array operations. I believe it will be very helpful for everyone to solve the program problems.
1. Nature
An array in JavaScript is a special object, and the index used to represent an offset is a property of the object, and the index may be an integer. However, these numeric indexes are internally converted to string type, because the attribute name in the JavaScript object must be a string.
2. Operation
1 Determine the array type
Copy the code 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));
// Consider compatibility, can be used
alert(array1 instance of Array);
// or
alert(Object.prototype.toString.call(array1) === '[object Array]');
2 array and string
Very simple: convert from an array to a string, use join; convert from a string to an array, use split.
Copy the code as follows:// join - Convert from array to string, use join
console.log(['Hello', 'World'].join(',')); // Hello,World
// split - convert from string to array, using split
console.log('Hello World'.split(' ')); // ["Hello", "World"]
3 Find elements
I believe that everyone often uses the string type indexOf, but rarely knows that the indexOf of an array can also be used to find elements.
Copy the code as follows:// indexOf - 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
From the above, we can see that for an array containing objects, the indexOf method does not obtain the corresponding search results through deep comparison, but only compares the references to the corresponding elements.
4 array connections
When using concat, be aware that a new array will be generated after using concat.
The code copy is as follows: var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); // After implementing array connection, a new array will be created
console.log(array3);
5 categories of list operations
To add elements, you can use push and unshift respectively, and to remove elements, you can use pop and shift respectively.
Copy the code 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 array header
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 method
Two main uses:
① Add and delete elements from the middle of the array
② Get a new array from the original array
Of course, the two uses are synthesized in one gas. Some scenarios focus on purpose one, while others focus on purpose two.
Add and delete elements from the middle position of the array. The splice method adds elements to the array. The following parameters are required.
① Start index (that is, where you want to start adding elements)
② The number of elements that need to be deleted or the number of elements extracted (the parameter is set to 0 when adding elements)
③ Elements you want to add to the array
The code copy 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 do the delete operation or extract a 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
The main introduction to reverse and sort methods. Array inversion uses reverse, the sort method can be used not only for simple sorting, but also for complex sorting.
Copy the code as follows:/ Invert 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 arrays of numeric elements
Copy the code as follows:/ If the array element is numerical type, the sort() method sorting result will not be satisfactory.
var nums = [3, 1, 2, 100, 4, 200];
nums.sort();
console.log(nums); // [1, 100, 2, 200, 3, 4]
The sort method sorts elements in dictionary order, so it assumes that elements are all string types, so even if the elements are numeric types, they are considered string types. At this time, you can pass a size comparison function when calling the method. When sorting, the sort() method will compare the sizes of two elements in the array based on the function, thereby determining the order of the entire array.
Copy the code 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
}
];
// Ascending order according to index for object elements in the array
var compare = function(o1, o2) {
return o1.index > o2.index;
};
objInArray.sort(compare);
console.log(objInArray[0].index <objInArray[1].index); // true
8 Iterator method
Mainly includes forEach and every, some and map, filter
I believe everyone can do it forEach, and I will mainly introduce the other four methods.
The every method accepts a function with a Boolean return value, which is used for each element in the array. If the function returns true for all elements, the method returns true.
The code copy is as follows: var nums = [2, 4, 6, 8];
// Iterator method that does not generate new arrays
var isEven = function(num) {
return num % 2 === 0;
};
// If all are even numbers, return true
console.log(nums.every(isEven)); // true
Some method also accepts a function with a Boolean return value. 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 map and filter methods can produce new arrays. The new array returned by map is the result of applying a function to the original element. like:
Copy the code 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 with a Boolean return value. Unlike the every() method, when the function is applied to all elements in the array and the result is true, the method does not return true, but returns a new array that contains the elements whose result is true after the function is applied.
Copy the code 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
The above also has the problem that some methods are not supported in 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. Everyone might as well pay more attention.
I hope this article will be helpful to everyone's JavaScript programming.