What is an array
- Is an ordered set of values
- Each value is called an element
- The numeric position of each element in the array is called an index
- Each JVAScript array has a length attribute
- Arrays are special forms of objects. Array indexes are similar to integer attribute names. Array implementations are optimized to use numeric indexes to access array elements much faster than regular object attributes
Array creation
- Let arr=[1,3,3,4,,]
- Let a=new Array(10)
Create array of specified length, preallocate array space; There are no stored values and index attributes are not defined
- Constructor explicitly specifies let a =new Array(3,2,4,2,8)
Array as a constructor behaves very inconsistently. Therefore, it is not recommended to use it to generate new arrays; it is better to use array literals directly.
The sparse array
define
- An array containing discontinuous indexes starting at 0
- The length of the array is greater than the number of elements
Sparse array creation
- Array() constructor creates new Array(4)
- Simply specify an array index greater than the current array length to create a[10000]=9275389
Undefined is not a sparse array
The addition and removal of array elements
Add an array element
- Add one or more elements to the end
a.push('one','two') a[length]='three' Copy the code
- Insert one element at the head of the array and move the others to the higher index –unshift()
Deleting an array element
- End delete pop ()
- Use an array to reduce the end of the array by 1 and return the value of the deleted element
- Delete shift ()
- Removes an element from the array header, moving all elements down 1 below the current index
- Generic methods for inserting, deleting, or replacing elements
- Splice ()
Modify the Length attribute and move the element to a higher or lower index as needed
- Delete delete
delete a[1]
Does not change the array length attribute, nor does it move elements down from the high index to fill in the whitespace left by the deleted attribute to a sparse array
- Splice ()
A static method
Array.isArray()
Returns a Boolean value indicating whether the argument is an array, which compensates for the Typeof operator
Instance methods
reduce(),reduceRight()
Reduce is processed from left to right (first member to last member)
[1, 2, 3, 4, 5].reduce(function (a, b) { console.log(a, b); return a + b; }) // 1 2/3 3 // 6 4 // 10 5 // Final result: 15Copy the code
parameter
- Cumulative variable, which defaults to the first member of the array
- Current variable, which defaults to the second member of the array
- Current position (starting from 0)
- The original array
// If you want to specify an initial value for the cumulative variable, you can place it in the second argument to the reduce and reduceRight methods. [1, 2, 3, 4, 5].reduce(function (a, b) { return a + b; }, 10); / / 25Copy the code
ReduceRight goes right to left (from the last member to the first member), and everything else is exactly the same.
function subtract(prev, cur) {
return prev - cur;
}
[3, 2, 1].reduce(subtract) // 0
[3, 2, 1].reduceRight(subtract) // -4
Copy the code
Reduce method is equivalent to 3 minus 2 and then minus 1, reduceRight method is equivalent to 1 minus 2 and then minus 3.
The treasure of reduce usage
- For maximum
var max = a.reduce((x,y)=>{return x>y? x:y})Copy the code
- An array of quadrature
var product=a.reduce((x,y)=>{return x*y},1)
Copy the code
- Array sum
Var a = [1, 2, 3, 4, 5] var sum = a.r educe ((x, y) = > {return x + y}, 0)Copy the code
- And set
var obj=[{x:1},{y:2}]
var merged=object.reduce(union)//=>{x:1,y:2}
Copy the code
splice()
Used to delete a part of the original array, and can add a new array member at the deleted location, the return value is the deleted element. Note that this method changes the original array.
arr.splice(start, count, addElement1, addElement2, ...) ;Copy the code
The first argument to splice is the starting position of the deletion (starting from 0), and the second argument is the number of elements to be deleted. If there are more arguments, these are the new elements to be inserted into the array.
General usage
var a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.splice(4, 2) // ["e", "f"]
a // ["a", "b", "c", "d"]
Copy the code
If the starting position is negative, it is deleted from the reciprocal position
var a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.splice(-4, 2) // ["c", "d"]
Copy the code
Simply inserting elements, the second argument to the splice method can be set to 0.
Providing only the first parameter is equivalent to splitting the array into two arrays at the specified location.
sort()
The sort method sorts the group members by lexicographical order by default. After sorting, the original array will be changed.
['d', 'c', 'b', 'a'].sort()
// ['a', 'b', 'c', 'd']
[4, 3, 2, 1].sort()
// [1, 2, 3, 4]
[11, 101].sort()
// [101, 11]
[10111, 1101, 111].sort()
// [10111, 1101, 111]
Copy the code
Custom sorting mode
[10111, 1101, 111].sort(function (a, b) { return a - b; }) / / [111, 1101, 10111] [{name: "zhang", the age: 30}, {name: "bill", the age: 24}, {name: "detective", the age: 28 } ].sort(function (o1, o2) { return o1.age - o2.age; }) / / / / / {name: "bill", the age: 24}, / / {name: "detective", the age: 28}, / / {name: "zhang", the age: 30} / /]Copy the code
Since the childhood
[{name: "zhang", the age: 30}, {name: "bill", the age: 24}, {name: "detective", the age: 28 } ].sort(function (o1, o2) { return o2.age - o1.age; })Copy the code
From big to small
[{name: "zhang", the age: 30}, {name: "bill", the age: 24}, {name: "detective", the age: 28 } ].sort(function (o1, o2) { return o2.age - o1.age; })Copy the code
out-of-order
Var arr = [1,2,3,4,5,6,7,8,9,], r = arr.sort(function(){return math.random () >.5? - 1:1; });Copy the code
valueOf(),toString()
- All objects have methods, and the valueOf method of an array returns the array itself
- The toString method returns an array as a string
var arr = [1, 2, 3]; Arr. ToString () / / "1, 2, 3" var arr = [1, 2, 3, [4, 5, 6]]. Arr. ToString () / / "6"Copy the code
Push () and pop ()
- The push method is used to add one or more elements to the end of an array and return the length of the array after the addition of new elements. This method alters the array
- The pop method is used to remove the last element of the array and return it. Note that this method changes the original array.
Unshift (), the shift ()
- The unshift() method is used to add an element to the first position of the array and returns the length of the array after the new element is added. Note that this method changes the original array.
- The shift() method is used to remove the first element of the array and return that element. Note that this method changes the original array.
join()
var a = [1, 2, 3, 4]; A. oin (' ') / / '1, 2, 3, 4, a. oin (' |') / / "1 | 2 | 3 | 4" a. oin () / / "1, 2, 3, 4"Copy the code
-
If the array member is undefined or null or empty, it is converted to an empty string.
-
Handy call method: concatenates all array members as a string with the specified parameter as the delimiter, which can be used for strings or array-like objects.
Array.prototype.join.call('hello', '-')
// "h-e-l-l-o"
var obj = { 0: 'a', 1: 'b', length: 2 };
Array.prototype.join.call(obj, '-')
// 'a-b'
Copy the code
concat()
- The concat method is used to merge multiple arrays. It adds the new array member to the back of the original array member, and returns a new array, unchanged.
- In addition to arrays as arguments, concat also accepts other types of values as arguments to be added to the end of the target array.
[1, 2, 3].concat(4, 5, 6)
// [1, 2, 3, 4, 5, 6]
Copy the code
reverse()
- Used to invert array elements to return the changed array.
- Note that this method changes the original array.
slice()
- Retrieves a portion of the target array, returning a new array, unchanged.
arr.slice(start, end);
- Its first argument is the start position (starting at 0) and its second argument is the end position (but not the element itself). If you omit the second argument, you are returned to the last member of the original array.
- If the slice method argument is negative, it indicates the position at which the reciprocal is evaluated
var a = ['a', 'b', 'c']; A.s lice (2) / / / "b", "c" a.s lice (2, 1) / / / "b"] / / - 2 in inverse calculation of the second position, 1 in inverse calculation of the first position.Copy the code
- If the first argument is greater than or equal to the length of the array, or if the second argument is less than the first argument, the empty array is returned
Important application: Turn array-like objects into real arrays.
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })
// ['a', 'b']
Array.prototype.slice.call(document.querySelectorAll("div"));
Array.prototype.slice.call(arguments);
Copy the code
None of the arguments in the above code are arrays, but they can be turned into real arrays by calling the Slice method on them with the call method
map()
- Pass all the members of the array to the argument function, and return the result of each execution as a new array
- The map method takes a function as an argument. When this function is called, the map method passes it three parameters: the current member, the current location, and the array itself
[1, 2, 3].map(function(elem, index, arr) { return elem * index; }); / / [0, 2, 6]Copy the code
- The map method can also take a second argument to bind the this variable inside the callback function
- If the array is empty, the map callback does not execute at that location and skips the array empty
var f = function (n) { return 'a' };
[1, undefined, 2].map(f) // ["a", "a", "a"]
[1, null, 2].map(f) // ["a", "a", "a"]
[1, , 2].map(f) // ["a", , "a"]
Copy the code
- The map method does not skip undefined and NULL, but does skip empty Spaces
forEach()
The forEach method does not return a value, but only manipulates data
If the purpose of array traversal is to get the return value, use the map method, otherwise use the forEach method.
- ForEach is used in the same way as the map method. The argument is a function that again takes three arguments: the current value, the current position, and the entire array
- The forEach method can also take a second argument, binding the this variable of the argument function
- The forEach method also skips arrays of empty Spaces.
- Undefined and NULL will not be skipped, but empty space will be skipped
filter()
- Used to filter the members of an array. The members that meet the criteria are returned as a new array
[1, 2, 3, 4, 5].filter(function (elem) { return (elem > 3); }) / / [4, 5]Copy the code
- The parameter function of the filter method can take three arguments: the current member, the current position, and the entire array
[1, 2, 3, 4, 5].filter(function (elem, index, arr) { return index % 2 === 0; }); / / [1, 3, 5]Copy the code
- You can also take a second argument to bind the this variable inside the argument function
some(),every()
- The some method returns true as long as one member returns true, and false otherwise.
- The every method returns true for all members, and false otherwise.
indexOf(),lastIndexOf()
These two methods cannot be used to search for NaN locations, that is, they cannot determine whether an array member contains a NaN.
This is because internally, the two methods are compared using the strict equality operator (===), and NaN is the only value that is not equal to itself.
- The indexOf method returns the position of the first occurrence of a given element in the array, or -1 if none occurs
var a = ['a', 'b', 'c'];
a.indexOf('b') // 1
a.indexOf('y') // -1
Copy the code
- The indexOf method can also accept a second parameter, indicating the starting point of the search.
['a', 'b', 'c'].indexOf('a', 1) // -1
Copy the code
- The lastIndexOf method returns the last occurrence of a given element in the array, or -1 if none occurred.
var a = [2, 5, 9, 2];
a.lastIndexOf(2) // 3
a.lastIndexOf(7) // -1
Copy the code
The chain using
Many of the array methods return arrays, so they can be chained
var users = [
{name: 'tom', email: '[email protected]'},
{name: 'peter', email: '[email protected]'}
];
users
.map(function (user) {
return user.email;
})
.filter(function (email) {
return /^t/.test(email);
})
.forEach(function (email) {
console.log(email);
});
// "[email protected]"
Copy the code