Arrays are often collated by functions
Summary: zh.javascript.info/
Array manipulation pop/push/shift/unshift:
push
Add an element at the end.shift
Take the first element of the queue, and the whole queue moves forward, so that the second element is now first.pop
Take an element from the end.unshift
Add an element to the beginning of an array:
Each of these methods changes the array
pop
Retrieves and returns the last element of the array:
let fruits = ["Apple"."Orange"."Pear"];
alert( fruits.pop() ); // Remove "Pear" and the alert is displayed
alert( fruits ); // Apple, Orange
Copy the code
push
Add an element to the end of the array:
let fruits = ["Apple"."Orange"];
fruits.push("Pear");
alert( fruits ); // Apple, Orange, Pear
Copy the code
shift
Take the first element of the array and return it:
let fruits = ["Apple"."Orange"."Pear"];
alert( fruits.shift() ); // Remove Apple and alert is displayed
alert( fruits ); // Orange, Pear
Copy the code
unshift
Add an element to the beginning of an array:
let fruits = ["Orange"."Pear"];
fruits.unshift('Apple');
alert( fruits ); // Apple, Orange, Pear
Copy the code
The push and unshift methods can both add multiple elements at once:
let fruits = ["Apple"];
fruits.push("Orange"."Peach");
fruits.unshift("Pineapple"."Lemon");
// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]
alert( fruits );
Copy the code
Array methods
splice
It changes the array
Arr. Splice (start[, deleteCount, elem1,... elemN]) It alters' arr 'from index' start 'by deleting' deleteCount 'and inserting' elem1,... , elemN `. Finally returns an array of deleted elements.Copy the code
Example:
Use 1:
1 / / usage
let arr = ["I"."study"."JavaScript"];
console.log(arr.splice(1.1)); ; // ['study']
console.log(arr); // ["I", "JavaScript"]
Copy the code
Usage 2: Remove and replace
let arr = ["I"."study"."JavaScript"."right"."now"];
// Remove the first three items of the array and replace them with something else
arr.splice(0.3."Let's"."dance");
alert( arr ) // Now ["Let's", "dance", "right", "now"]
Copy the code
Usage 3: Add, set the second parameter to 0, you can add (note added before)
let arr = ["I"."study"."JavaScript"."right"."now"];
arr.splice(1.0."Let's"."dance");
console.log( arr);/ / now [' I ', 'Let' s' and 'dance', 'study', 'JavaScript' and 'right' and 'now']
Copy the code
Usage 4: Negative indexes are allowed,
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
slice
It doesn’t change the array
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.
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
Other uses:
// Array copy
let arr = [1.2.3];
// Do not pass parameters
let arr2 = arr.slice()
alert(arr2)/ / [1, 2, 3]
Copy the code
concat
Creates a new array containing values from other arrays and other items.
Grammar:
arr.concat(arg1, arg2...)
Copy the code
Concat () can contain arrays and values
let arr = [1.2];
console.log( arr.concat([3.4]));/ / 1, 2, 3, 4
console.log( arr.concat([3.4], [5.6]));/ / 6
console.log( arr.concat([3.4]."5".true.null.undefined.12, {name:"we"},v= >v) ); / / [1, 2, 3, 4, '5', true, null, and undefined, 12, {...}, ƒ]
Copy the code
If such an array of objects with Symbol. IsConcatSpreadable attribute, it will be as an array concat to deal with
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
forEach()
arr.forEach(function(item, index, array) {
// ... do something with item
});
Copy the code
Search in array
IndexOf/lastIndexOf and includes
arr.indexOf(item, from)
From the indexfrom
Begin your searchitem
, returns the index if found, otherwise returns- 1
.arr.lastIndexOf(item, from)
Same as above, but search from right to left.arr.includes(item, from)
From the index —from
Begin your searchitem
, returns if foundtrue
If not found, returnfalse
).
== These methods use strict equality === comparisons. So if we search for false, it will be true false and not the number zero. = =
Includes handles NaN correctly
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
The find grammar:
let result = arr.find(function(item, index, array) {
// If true is returned, item is returned and iteration stops
// In case of falsy, undefined is returned
});
/* - 'item' is the element. - 'index' is its index. - 'array' is the array itself. * /
/ / usage
//find returns only the first element found
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
The arr.findIndex method is basically the same as the arr.find method, but it returns the index of the found element rather than the element itself. And returns -1 if nothing is found.
filter
Find can find only one element, and filter can find all matching elements
Grammar:
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
Usage:
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
Array processing
**map
It changes the array
It calls a function on each element of the array and returns an array of results.
let result = arr.map(function(item, index, array) {
// Returns the new value instead of the current element
})
Copy the code
let lengths = ["Bilbo"."Gandalf"."Nazgul"].map(item= > item.length);
alert(lengths); / / 5,7,6
Copy the code
sort
Sort an array in situ, that is, sort within the array instead of generating a new array
Sort converts elements to string sort if no arguments are passed:
let arr = [ 1.2.15 ];
// This method rearranges the contents of the ARR
arr.sort();
alert( arr ); / / 1, 15, 2
Copy the code
Normally you pass in a function that returns a positive, zero, or negative number
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
}
let arr = [ 1.2.15 ];
arr.sort(compareNumeric);
alert(arr); / / 1, 2, 15
/ / simplified:
arr.sort( (a, b) = > a - b );
Copy the code
From small to large A-B from large to small B-A;
reverse
Reversing array elements
let arr = [1.2.3.4.5];
arr.reverse();
alert( arr ); / / 5,4,3,2,1
Copy the code
split
Splits a string into an array with the given delimiter
let names = 'Bilbo, Gandalf, Nazgul';
let arr = names.split(', ');
console.log(arr);//['Bilbo', 'Gandalf', 'Nazgul']
Copy the code
The second argument can specify the length of the array to cut the excess:
let names = 'Bilbo, Gandalf, Nazgul';
let arr = names.split(', '.1);
console.log(arr);// ['Bilbo']
Copy the code
join
As opposed to split, it can glue an array into a string
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
reducer
It’s essentially an accumulator
grammar
let value = arr.reduce(function(accumulator, item, index, array) {
// ...
}, [initial]);
/* - 'accumulator' -- is the result of the previous function call and is first equal to 'initial' (if provided). - 'item' - The current array element. - 'index' -- The current index. - 'arr' -- the array itself. * /
Copy the code
Add with Reducer:
let arr = [1.2.3.4.5];
let result = arr.reduce((sum, current) = > sum + current, 0);
alert(result); / / 15
Copy the code
If no initial value is passed, == Then the initial value of Accumulator is ARR [0],item value is ARR [1], and index is 1==
There is also a redueRight method that uses the same method as reducer, but traverses from right to left
A method to determine an array
Array.isArray(arr); // true
arr.__proto__ === Array.prototype; // true
arr instanceof Array; // true
Object.prototype.toString.call(arr); // "[object Array]"
Copy the code
Other methods
Array.form
The ** array.from ()** method creates a new, shallow-copy instance of an array-like or iterable.
fill
The **fill()** method fills all elements in an array from the start index to the end index with a fixed value. Does not include terminating indexes.
const array1 = [1.2.3.4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0.2.4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5.1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
Copy the code
Common function collation of strings
Change case
ToLowerCase () and toUpperCase ()
alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface
Copy the code
Find string
str.indexOf
The first method is str.indexof (substr, pos):== It starts at the given position pos, looks for substr in STR, and returns -1 if none is found, otherwise returns the successful position ==.
Includes, startsWith, endsWith
Str.includes (substr, pos) returns true/false depending on whether the STR contains substr.
If we need to detect a match, but don’t need its location, then this is the right choice:
alert( "Widget with id".includes("Widget"));// true
alert( "Hello".includes("Bye"));// false
Copy the code
The second optional argument to str.includes is the starting location to start the search:
alert( "Midget".includes("id"));// true
alert( "Midget".includes("id".3));// false, no "id" from position 3
Copy the code
The str.startswith and str.endswith methods do what their names suggest:
alert( "Widget".startsWith("Wid"));// true, "Widget" starts with "Wid"
alert( "Widget".endsWith("get"));// true, "Widget" ends with "get"
Copy the code
Get string
str.slice(start [, end])
Returns the portion of the string from start to (but not including) end.
Such as:
let str = "stringify";
alert( str.slice(0.5));// 'strin', substring from 0 to 5 (excluding 5)
alert( str.slice(0.1));// 's', from 0 to 1, but not including 1, so only characters at 0
Copy the code
Without the second argument, slice runs until the end of the string:
let str = "stringify";
alert( str.slice(2));// From the second position to the end
Copy the code
Start /end can also be negative. They mean that the starting position is computed from the end of the string:
let str = "stringify";
// Start at the fourth position on the right and finish at the first position on the right
alert( str.slice(-4, -1));// 'gif'
Copy the code
str.substring(start [, end])
Returns the part of the string between start and end.
This is almost the same as slice, but it allows start to be greater than end.
Such as:
let str = "stringify";
// These are the same for substring
alert( str.substring(2.6));// "ring"
alert( str.substring(6.2));// "ring"
/ /... But it's different for Slice:
alert( str.slice(2.6));// "ring"
alert( str.slice(6.2));// "" (empty string)
Copy the code
Negative arguments are not supported (unlike slice), they are treated as 0.
str.substr(start [, length])
Returns the portion of the string starting at start with a given length.
Compared to the previous method, this allows us to specify length instead of end position:
let str = "stringify";
alert( str.substr(2.4));// 'ring', starting at position 2, gets 4 characters
Copy the code
The first argument may be negative, counting from the end:
let str = "stringify";
alert( str.substr(-4.2));// 'gi', gets 2 characters from the 4th bit
Copy the code
Other methods
-
str.codePointAt(pos)
Alert (“z”. CodePointAt (0)); // 122 alert( “Z”.codePointAt(0) ); / / 90
-
String.fromCodePoint(code)
Create character alert(string.fromcodePoint (90)) with numeric code; // Z we can also add unicode characters with \u followed by hexadecimal codes: // In the hexadecimal system 90 is 5a alert(‘\u005a’); // Z
-
str.trim()
The trim() method removes whitespace characters from both ends of a string. Whitespace characters in this context are all whitespace characters (space, TAB, no-break space, etc.) and all line terminator characters (such as LF, CR, etc.).