Compiled from modern JavaScript tutorials
Array introduction and understanding
An array is a sequential collection of data stored consecutively in memory space.
Initialize an array
let arr = new Array(a);// Instantiate the Array object
let arr = [];
Copy the code
Get the data in the array by index
let fruits = ["Apple"."Orange"."Plum"];
alert( fruits[0]);// Apple
fruits[2] = 'Pear'; // Now it's ["Apple", "Orange", "Pear"]
fruits[3] = 'Lemon'; // Now becomes ["Apple", "Orange", "Pear", "Lemon"]
let fruits = ["Apple"."Orange"."Plum"];
alert( fruits.length ); // 3 length is the length of the array, or the subscript of the last element of the array +1.
Copy the code
The easiest way to empty an array is to: arr. Length = 0; .
JavaScript array features
- The length of the array is not fixed
- The archetype of an array is an object, and an array is basically an object
- Arrays can hold various types of data
Basic array manipulation methods
-
pop/push
Remove/add an element at the end
-
shift/unshift
Removes/adds an element in the header
-
Removing elements by pop and Shift returns the removed element, adding does not
-
Operations in the header are slower than operations in the tail, because adding or deleting in the header moves subsequent elements, while operations in the tail do not
Through the array
- The for loop iterates
let arr = ["Apple"."Orange"."Pear"];
for (let i = 0; i < arr.length; i++) {
alert( arr[i] );
}
Copy the code
- for … of … traverse
let fruits = ["Apple"."Orange"."Plum"];
// Iterate over the array of elements
for (let fruit of fruits) {
alert( fruit );
}
Copy the code
for .. of .. Get only elements, not indexes
Multidimensional array
let matrix = [
[1.2.3],
[4.5.6],
[7.8.9]]. alert( matrix[1] [1]);// The middle number
Copy the code
Array toString () method
Arrays have their own implementation of the toString method, which returns a comma-separated list of elements.
let arr = [1.2.3];
alert( arr ); / / 1, 2, 3
alert( String(arr) === '1, 2, 3' ); // true
alert( [] + 1 ); / / "1"
alert( [1] + 1 ); / / "11"
alert( [1.2] + 1 ); // "1,21" triggers string concatenation
Copy the code
Array manipulation in depth
Arr.splice (Add, replace, delete elements)
The arr.splice method is the Swiss Army knife of arrays. It can do everything: add, delete, and insert elements.
grammar
arr.splice(start[, deleteCount, elem1, ..., elemN])
Copy the code
It modifies arR from index start by removing the deleteCount element and inserting elem1 at the current position (the start position)… , elemN. Finally returns an array of deleted elements.
use
We can set deleteCount to 0, and the splice method inserts elements without deleting any:
let arr = ["I"."study"."JavaScript"];
// Start with index 2
// Delete 0 elements
// Then insert "complex" and "language" (at index 2)
arr.splice(2.0."complex"."language");
alert( arr ); // "I", "study", "complex", "language", "JavaScript"
Copy the code
Negative indexes are allowed
In this and other array methods, negative indexes are allowed. They compute positions from the end of the array as follows:
let arr = [1.2.5];
// From index -1 (the first digit at the end)
// Delete 0 elements,
// Then insert 3 and 4
arr.splice(-1.0.3.4);
alert( arr ); / / 1, 2, 3, 4, 5
Copy the code
The negative lookup position index starts at -1 and inserts are positive
Arr. Slice (copy part of array to new array)
grammar
arr.slice([start], [end])
Copy the code
It returns a new array, copying all items from index start to end (excluding end) into a new array. Both start and end can be negative numbers, in which case the index is calculated from the end.
use
let arr = ["t"."e"."s"."t"];
alert( arr.slice(1.3));E,s (copy elements from position 1 to position 3)
alert( arr.slice(-2));// s,t (copy elements from position -2 to the end)
Copy the code
If it is called without arguments, it returns a copy of the array
The order of the elements represented by the two arguments must be the first, otherwise an empty array is returned
Arr. Concat (copies the passed arguments into an array)
grammar
arr.concat(arg1, arg2...)
Copy the code
Arr. Concat creates a new array containing values from other arrays and other items.
use
let arr = [1.2];
// create an array from: arr and [3,4]
alert( arr.concat([3.4]));/ / 1, 2, 3, 4
Create an array from: arr and [3,4] and [5,6]
alert( arr.concat([3.4], [5.6]));/ / 6
// create an array from: arr and [3,4], then add values 5 and 6
alert( arr.concat([3.4].5.6));/ / 6
Copy the code
Pay attention to
In general, it copies only the elements in the array. Other objects, even if they look like arrays, will still be added as a whole
let arr = [1.2];
let arrayLike = {
0: "something".length: 1
};
alert( arr.concat(arrayLike) ); / / 1, 2, [object object]
Copy the code
If such an array of objects with Symbol. IsConcatSpreadable attribute, it will be as an array concat to handle: element of this object will be added
let arr = [1.2];
let arrayLike = {
0: "something".1: "else"[Symbol.isConcatSpreadable]: true.length: 2
};
alert( arr.concat(arrayLike) ); / / 1, 2, something else
Copy the code
Arr. ForEach (runs a function forEach element in the array)
grammar
arr.forEach(function(item, index, array) {
// ... do something with item
});
Copy the code
The arr. ForEach method allows you to run a function forEach element of an array.
use
["Bilbo"."Gandalf"."Nazgul"].forEach((item, index, array) = > {
alert(`${item} is at index ${index} in ${array}`);
});
Copy the code
The result of this function (if it returns anything) is discarded and ignored.
Search through an array
IndexOf/lastIndexOf and includes
Arr.indexof, arr.lastIndexof, and arr.includes methods
-
Arr.indexof (item, from) Searches for an item starting from the index from, returning the index if found, or -1 otherwise.
-
Arr.lastindexof (item, from) — same as above, but search from right to left.
-
Arr.includes (item, from) – Searches for items from the index from and returns true if found.
Such as:
let arr = [1.0.false];
alert( arr.indexOf(0));/ / 1
alert( arr.indexOf(false));/ / 2
alert( arr.indexOf(null));// -1
alert( arr.includes(1));// true
Copy the code
Note that these methods use strict equality === comparisons. So if we search for false, it will be true false and not the number zero.
If we want to check whether an element is included and don’t want to know the exact index, arr.includes is the first choice.
Also, a very small difference in includes is that it handles NaN correctly, unlike indexOf/lastIndexOf:
const arr = [NaN];
alert( arr.indexOf(NaN));// -1 (should be 0, but strictly equal === NaN)
alert( arr.includes(NaN));// true
Copy the code
Find and findIndex
Arr. Find methods.
The syntax is as follows:
let result = arr.find(function(item, index, array) {
// If true is returned, item is returned and iteration stops
// For false, undefined is returned
});
Copy the code
Call this function on each element in the array in turn:
item
Is the element.index
It’s its index.array
It’s the array itself.
If it returns true, the search stops and item is returned. If none is found, undefined is returned.
For example, we have an array of users, each with id and name fields. Let’s find the user whose id == 1:
let users = [
{id: 1.name: "John"},
{id: 2.name: "Pete"},
{id: 3.name: "Mary"}];let user = users.find(item= > item.id == 1);
alert(user.name); // John
Copy the code
Note that in this example, we passed find a single-argument function item => item.id == 1. This is typical, and the other parameters of the find method are rarely used.
Arr. FindIndex method
The arr.find method is basically the same, but it returns the index of the element found, not the element itself. And returns -1 if nothing is found.
Filter (makes the function returntrue
The first (single) element of
find
If we need to match a lot, we can use arr.filter(fn).
The syntax is much the same as find, but filter returns an array of all matched elements:
let results = arr.filter(function(item, index, array) {
// If true item is pushed to Results, the iteration continues
// Return an empty array if nothing is found
});
Copy the code
Such as:
let users = [
{id: 1.name: "John"},
{id: 2.name: "Pete"},
{id: 3.name: "Mary"}];// Returns an array of the first two users
let someUsers = users.filter(item= > item.id < 3);
alert(someUsers.length); / / 2
Copy the code
Convert an array
Map (calls a function on each element of an array and returns an array of results)
The arr.map method is one of the most useful and frequently used.
It calls a function on each element of the array and returns an array of results.
Grammar:
let result = arr.map(function(item, index, array) {
// Returns the new value instead of the current element
})
Copy the code
For example, here we convert each element to its string length:
let lengths = ["Bilbo"."Gandalf"."Nazgul"].map(item= > item.length);
alert(lengths); / / 5,7,6
Copy the code
Sort (fn) (sort within this array)
The arr.sort method sorts an array in-place, changing the order of the elements. (In situ means inside the array, not generating a new array.)
It also returns the sorted array, but the return value is usually ignored because the ARR itself has been modified.
Grammar:
let arr = [ 1.2.15 ];
// This method rearranges the contents of the ARR
arr.sort();
alert( arr ); / / 1, 15, 2
Copy the code
These elements are sorted by string by default.
Literally, all elements are converted to strings and then compared. For strings, the lexicographic sort should actually be “2” > “15”.
To use our own sort order, we need to supply a function as an argument to arr.sort().
This function should compare two arbitrary values and return:
function compare(a, b) {
if (a > b) return 1; // If the first value is greater than the second value
if (a == b) return 0; // If two values are equal
if (a < b) return -1; // If the first value is smaller than the second
}
Copy the code
For example, sort by number:
function compareNumeric(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}
let arr = [ 1.2.15 ];
arr.sort(compareNumeric);
alert(arr); / / 1, 2, 15
Copy the code
Now the results are in line with expectations.
An ARR can be an array of anything, including numbers, strings, objects, or anything else. We have a set of elements. To sort it, we need a sorting function to confirm how these elements are compared. The default is to sort by string.
The arr.sort(fn) method implements a general sorting algorithm. We don’t need to worry about its inner workings (most of which are optimized by quicksort or Timsort algorithms). It will iterate over the array, compare its elements and reorder them using the provided function, and all we need is to provide the function fn to perform the comparison.
By the way, if we want to know which elements to compare — then nothing stops us from alerting them:
[1, -2.15.2.0.8].sort(function(a, b) {
alert( a + "< >" + b );
return a - b;
});
Copy the code
The algorithm can compare one element to multiple other elements along the way, but it tries to do as few comparisons as possible.
The comparison function can return any number
In fact, the comparison function simply returns a positive number for greater than and a negative number for less than.
Using this principle we can write shorter functions:
let arr = [ 1.2.15 ];
arr.sort(function(a, b) { return a - b; });
alert(arr); / / 1, 2, 15
Copy the code
Arrow function is best
arr.sort( (a, b) = > a - b );
Copy the code
This is exactly the same as the longer version above.
uselocaleCompare
for strings
Do you remember string comparison algorithms? By default, it compares letters by their code.
For many letters, it is best to sort the letters correctly using the str.localecompare method, such as O.
For example, let’s sort several countries/regions in German:
let countries = ['Österreich'.'Andorra'.'Vietnam'];
alert( countries.sort( (a, b) = > a > b ? 1 : -1));// Andorra, Vietnam, Osterreich
alert( countries.sort( (a, b) = > a.localeCompare(b) ) ); // Andorra, Osterreich,Vietnam
Copy the code
Reverse (reversing the order of elements in an array)
The arr.reverse method is used to reverse the order of elements in an ARR.
Such as:
let arr = [1.2.3.4.5];
arr.reverse();
alert( arr ); / / 5,4,3,2,1
Copy the code
It also returns the array ARr reversed.
Split and join (split strings into arrays)
The str.split(delim) method splits the string into an array with the given delimiter delim.
In the following example, we use “comma followed by a space” as the delimiter:
let names = 'Bilbo, Gandalf, Nazgul';
let arr = names.split(', ');
for (let name of arr) {
alert( `A message to ${name}. ` ); // A message to Bilbo (and other names)
}
Copy the code
The split method takes an optional second numeric argument — a limit on the length of the array. If provided, additional elements are ignored. But in practice it is rarely used:
let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', '.2);
alert(arr); // Bilbo, Gandalf
Copy the code
Split into letters
Calling split(s) with the empty argument s splits the string into alphabetic arrays:
let str = "test";
alert( str.split(' '));// t,e,s,t
Copy the code
Arr. join(glue) is the opposite of split. It creates a string of ARR items that glue between them.
Such as:
let arr = ['Bilbo'.'Gandalf'.'Nazgul'];
let str = arr.join('; '); // Use a semicolon; Glue an array into a string
alert( str ); // Bilbo; Gandalf; Nazgul
Copy the code
reduce/reduceRight
When we need to iterate over an array — we can use forEach, for, or for.. Of.
When we need to traverse and return data for each element — we can use map.
The Arr. Reduce and Arr. ReduceRight methods are similar to the above but slightly more complex. They are used to evaluate a single value from an array.
Grammar is:
let value = arr.reduce(function(accumulator, item, index, array) {
// ...
}, [initial]);
Copy the code
This function is applied to all array elements one by one and “carries on” its results to the next call.
Parameters:
accumulator
— is the result of the previous function call, the first time equalsinitial
(If providedinitial
).item
— The current array element.index
— Current index.arr
— The array itself.
When a function is applied, the result of the previous function call is passed to the next function as the first argument.
Therefore, the first parameter is essentially an accumulator, used to store the results of all previously executed combinations. Finally, it becomes the result of Reduce.
The easiest way to learn this is by example.
Here, we get the sum of an array with one line of code:
let arr = [1.2.3.4.5];
let result = arr.reduce((sum, current) = > sum + current, 0);
alert(result); / / 15
Copy the code
The function passed to Reduce takes only two arguments, which is usually enough.
Let’s look at the details, what happened.
- On the first run,
sum
Is the initial valueinitial
(reduce
Is equal to 0,current
Is the first element of the array, is equal to1
. So the result of the function running is theta1
. - On the second run,
sum = 1
, we call the second array element (2
) and return them. - On the third run,
sum = 3
, we add the next element to it, and so on…
Calculation process:
Or in table form, where each row represents a function call to the next array element:
sum |
current |
result |
|
---|---|---|---|
First call | 0 |
1 |
1 |
Second call | 1 |
2 |
3 |
Third call | 3 |
3 |
6 |
Fourth call | 6 |
4 |
10 |
Fifth call | 10 |
5 |
15 |
Here we can clearly see how the result of the previous call becomes the first argument to the next call.
We can also omit the initial value:
let arr = [1.2.3.4.5];
// Delete the initial reduce value (no 0)
let result = arr.reduce((sum, current) = > sum + current);
alert( result ); / / 15
Copy the code
The result is the same. This is because if there is no initial value, reduce takes the first element of the array as its initial value and iterates from the second element.
The calculation table is the same as above, except that the first row is removed.
But it needs to be used with great care. If the array is empty, calling reduce without an initial value will result in an error.
Such as:
let arr = [];
// Error: Reduce of empty array with no initial value
// If the initial value exists, reduce will return it for empty ARR.
arr.reduce((sum, current) = > sum + current);
Copy the code
Therefore, it is recommended to always specify an initial value.
ReduceRight and arr. Reduce have the same function except traversal from right to left.
Array.isArray
Arrays are object-based and do not constitute a separate language type.
So Typeof doesn’t help distinguish ordinary objects from arrays:
alert(typeof {}); // object
alert(typeof []); // same
Copy the code
… But arrays are often used, so there is a special way to determine: array.isarray (value). If value is an array, return true; Otherwise return false.
alert(Array.isArray({})); // false
alert(Array.isArray([])); // true
Copy the code
Most methods support “thisArg”
Almost all array methods that call functions — such as find, filter, map, with the exception of sort — accept an optional additional argument thisArg.
This parameter is not explained in the above section because it is rarely used. But for completeness, we need to talk about it.
Here is the full syntax for these methods:
arr.find(func, thisArg);
arr.filter(func, thisArg);
arr.map(func, thisArg);
// ...
ThisArg is the last optional argument
Copy the code
ThisArg argument becomes this in func.
For example, here we use the army object method as a filter and thisArg is used to pass the context:
let army = {
minAge: 18.maxAge: 27.canJoin(user) {
return user.age >= this.minAge && user.age < this.maxAge; }};let users = [
{age: 16},
{age: 20},
{age: 23},
{age: 30}];// Find army.canJoin user that returns true
let soldiers = users.filter(army.canJoin, army);
alert(soldiers.length); / / 2
alert(soldiers[0].age); / / 20
alert(soldiers[1].age); / / 23
Copy the code
If we had used users.filter(army.canjoin) in the above example, army.canJoin would have been called as a separate function, and this=undefined, resulting in an immediate error.
You can replace the call to users.filter(army.canjoin, army) with users.filter(user => army.canjoin (user)). The former is used more often because it is easier for most people to understand.
conclusion
Array methods cheat sheet:
- Add/Remove elements:
push(... items)
Add elements to the endpop()
Extract an element from the end,shift()
Extract an element from the header,unshift(... items)
Add element to headersplice(pos, deleteCount, ... items)
– frompos
To deletedeleteCount
Element and insertitems
.slice(start, end)
Create a new array that will be indexed fromstart
To the indexend
(But notend
) element.concat(... items)
Return a new array: copy all the elements of the current array and add to ititems
. ifitems
If any of the entries is an array, take its elements.
- Search elements:
indexOf/lastIndexOf(item, pos)
From the index —pos
Begin your searchitem
, returns the index of the item if found, otherwise returns- 1
.includes(value)
If the array hasvalue
, the returntrue
Otherwise returnfalse
.find/filter(func)
– byfunc
Filter the element and return thefunc
returntrue
The first value/all values of.findIndex
和find
Similar, but returns the index instead of the value.
- Traversal elements:
forEach(func)
Called on each elementfunc
Does not return anything.
- Conversion array:
map(func)
Call on each elementfunc
Creates a new array as a result of.sort(func)
Sort the array in-place, and return it.reverse()
Reverse the array in place and return it.split/join
Convert a string to an array and return it.reduce/reduceRight(func, initial)
By calling each elementfunc
Evaluates individual values on the array and passes intermediate results between calls.
- Other:
Array.isArray(arr)
checkarr
Is it an array?
Note that the sort, reverse, and splice methods modify the array itself.
These are the most common methods, covering 99% of use cases. But there are a few others:
-
Arr.some (fn)/arr.every(fn) checks arrays.
Similar to map, the function fn is called for each element of the array. Return true if any/all of the results are true, false otherwise.
The behavior of these two methods are similar to | | and && operator: if fn returns a true value, arr. Some () returns true immediately and stop the iteration the rest of the array; If fn returns a false value, arr.every() immediately returns false and stops iterating over the remaining array items.
We can use every to compare arrays:
function arraysEqual(arr1, arr2) { return arr1.length === arr2.length && arr1.every((value, index) = > value === arr2[index]); } alert( arraysEqual([1.2], [1.2])); // true Copy the code
-
Arr.fill (value, start, end) — From index start to end, fills the array with repeated values.
-
Arr.copywithin (target, start, end) — Copies all elements from position start to end to its target location (overwriting existing elements).
-
Arr.flat (depth)/arr.flatMap(fn) creates a new flat array from a multidimensional array.
-
Array.of(element0[, element1[,… [, elementN\]]]) creates a new Array instance based on a variable number of parameters, regardless of the number or type of parameters.