JavaScript arrays are commonly used as a collection of manipulation tips
- 2020-03-30 04:22:07
- OfStack
This example summarizes common techniques for manipulating JavaScript arrays. Share with you for your reference. The details are as follows:
preface
I'm sure you're all familiar with jquery or underscore and other array-related operations commonly used in libraries such as $.isarray, _.some, _.find, and so on. This is just a little more wrapping around the native js array operations.
Here is a summary of the common apis for JavaScript array operations. I think it will be very helpful to you to solve the procedural problems.
A, the nature,
An array in JavaScript is a special object that indicates that the index of the offset is an attribute of that object, and the index may be an integer. However, these numeric indexes are internally converted to string types because the property names in the JavaScript object must be strings.
Second, the operating
1 determines the array type
var array0 = []; //Literal
var array1 = new Array(); //Constructor
//Note: under ie6/7/8 is
that does not support the array.isarray method
alert(Array.isArray(array0));
//For compatibility, use
alert(array1 instanceof Array);
//Or < br / >
alert(Object.prototype.toString.call(array1) === '[object Array]');
2 arrays and strings
Very simple: from an array to a string, use a join; Converts a string to an array, using a split.
//Join - converts an array to a string, using join
console.log(['Hello', 'World'].join(',')); // Hello,World
//Split - converts a string to an array, using split
console.log('Hello World'.split(' ')); // ["Hello", "World"]
3 find elements
I'm sure you all use indexOf as a string, but you rarely know that indexOf of arrays can also be used to find elements.
//IndexOf - finds the 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
From the above, it can be seen that for an array containing objects, the indexOf method is not a deep comparison to get the corresponding lookup results, but just a comparison of the references of the corresponding elements.
4 array join
With concat, note that using concat generates a new array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //After the array concatenation is implemented, a new array
is created
console.log(array3);
5 class list operations
Use push and unshift to add elements, and pop and shift to remove elements.
// 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 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 remove elements from the middle of the array
From the original array, get a new array
Of course, the two USES are one-size-fits all, with some scenarios focusing on one and others on two.
7 the sorting
Reverse and sort methods are mainly introduced. Array inversion USES reverse, and the sort method can be used for complex sorts as well as simple sorts.
//Reverse the array
var array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array); // [5, 4, 3, 2, 1]
Let's sort the array of string elements first
var arrayOfNames = ["David", "Mike", "Cynthia", "Clayton", "Bryan", "Raymond"];
arrayOfNames.sort();
console.log(arrayOfNames); // ["Bryan", "Clayton", "Cynthia", "David", "Mike", "Raymond"]
We sort the array of number elements
//If array elements are numeric types, the sort() method's sorting results are not 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 lexicographical order, so it assumes that they are all string types, so even if they are numeric, they are considered string types. At this point, you pass in a size comparison function when you call a method, and when sorting, the sort() method compares the size of two elements in the array based on that function to determine the order of the entire array.
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
}
];
//For the object elements in the array, according to the index of the ascending order
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
It mainly contains forEach, every, some, map and filter
ForEach will, I'm sure, focus on four other methods.
The every method accepts a function with a return value of Boolean type, which is used for each element in the array. This method returns true if the function returns true for all elements.
var nums = [2, 4, 6, 8];
//Iterator method that does not generate a new array
var isEven = function(num) {
return num % 2 === 0;
};
//Returns true
if both are even
console.log(nums.every(isEven)); // true
some Method also accepts a function with a return value of 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 the map and filter methods generate new arrays, and the new array returned by the map is the result of applying a function to the original element. Such as:
var up = function(grade) {
return grade += 5;
}
var grades = [72, 65, 81, 92, 85];
var newGrades = grades.ma
The filter method is 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 instead returns a new array containing the elements that result in true when the function is applied.
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]
Third, summary
These are all common methods that you might not think of very easily. You might as well pay more attention.