A, judge the array method summary
-
Call () by the Object. The prototype. ToString.
Every Object that inherits Object has the toString method, which returns [Object type], where type is the type of the Object, if toString() is not overridden. However, when toString() is used directly for objects other than Object, it returns a string of contents, so we need to change the execution context of toString() using call or apply methods.
// This method evaluates all basic data types, even null and undefined; This is used to determine objects built into the browser. Object.prototype.toString.call(['Hello'.'An']); // "[object Array]" Object.prototype.toString.call('An') // "[object String]" Object.prototype.toString.call(1) // "[object Number]" Object.prototype.toString.call(Symbol(1)) // "[object Symbol]" Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(undefined) // "[object Undefined]" Object.prototype.toString.call(function(){}) // "[object Function]" Object.prototype.toString.call({name: 'An'}) // "[object Object]" Copy the code
-
Through the instanceof
[] instanceof Array; // true Copy the code
-
The instanceof principle returns true if it finds the prototype to which the constructor’s prototype refers in the instance’s prototype chain. That is:
// __proto__: represents the prototype object chaininstance.[__proto__...] === instance.constructor.prototype// return true Copy the code
-
-
Through the ES6 Array. IsArrray ()
function isArray(obj){return Array.isArrray(obj); }; Copy the code
-
Instanceof with isArray
Array.isArray is superior to instanceof when detecting Array instances because array. isArray can detect iframes
-
Array. IsArray () and the Object. The prototype. ToString. Call ()
Array. IsArray () is ES6 new method, when there is no Array. The isArray (), you can use the Object. The prototype. ToString. Call () implementation.
-
4. Judge by the prototype chain
5, through the Array. The prototype. IsPrototypeOf
2, array common methods
Join (): Generates a string by specifying a conjunction
2.1 the stack method
The stack is a last-in-first-out (LIFO) data structure, where the latest addition is removed earliest. Stack insertion (called push) and removal (called pop) occur in only one place — the top of the stack.
push() / pop()
: The end of the array is pushed and ejected, changing the original array;push
Returns the modified array length,pop
Returns the removed item.
2.2 Queue Method
The access rule for queue data structures is FIFO (first-in-first-out). Queues add items to the end of the list and remove items from the front of the list.
shift()
: Removes the first item in the array and returns that item, changing the array;unshift()
: Adds any item to the front of the array and returns the new array length, changing the original array.
2.3 Reordering method
-
Reverse () : Reverses the order of the array, changing the original array;
-
Sort () : The default is to sort the items in ascending order, but to sort, sort() calls each item’s toString() and compares the resulting strings, changing the array
var arr = [0.1.5.10.15]; arr.sort(); // arr=>[0, 1, 10, 15, 5] // the sort() method takes a comparison function as an argument; function compare(val1,val2){ return val1-val2; } arr.sort(compare); // arr => [0, 1, 5, 10, 15] Copy the code
2.4 Operation Methods
-
Concat (): You can create a new array based on all the items in the current array. That is, this method creates a copy of the current array, appends the received arguments to the end of the copy, and returns the newly constructed array. Concatenate array, (does not affect the original array), shallow copy
-
Slice (start, end) : Creates a new array based on one or more items in the current array. (Do not change the original array)
- Returns all entries from the position specified by the argument to the end of the current array.
- With two arguments, return the item between the start and end positions — but not the end position;
- If the argument has a negative value, the array length plus the number is used to determine the position. If the end position is less than the start position, return []
-
splice(start, number, value…) : Is used to insert items into the middle of an array, changing the original array
- Delete: specify 2 parameters, that is, the location of the first item to be deleted and the number of items to be deleted;
- Insert: Specifies three parameters, namely the starting position, 0 (number of items to delete), and the item to insert. Multiple items can be inserted;
- Replace: Specifies three parameters, namely the starting position, the number of items to delete, and any number of items to insert.
2.5 Location Method
indexOf / lastIndexOf(value, fromIndex)
: Finds the array entry and returns the corresponding subscript
2.6 Iterative method
Each method takes two parameters, the function to run on each item and the (optional) scoped object to run the function — affecting the value of this
The functions passed into these methods take three arguments: the value of the array item, the position of the item in the array, and the array object itself.
every()
: Returns true if the function returns true for each item;some()
: If the function returns on any itemtrue
, the returntrue
;filter()
: returns an array of items for which this function returns true;forEach()
: This method returns no value; Can’tbreak
, you can usetry/catch
In thethrow new Error
To stopmap()
: returns an array of the results of each function call;
2.7 Merging method
Both reduce() and reduceRight() iterate over all the items in the array and then build a value that is ultimately returned. Both take two arguments: a function called on each item and, optionally, the initial value as the basis for merging.
The function in the method takes four arguments: the previous value, the current value, the item’s index, and the array object; Any value returned by this function is automatically passed to the next item as the first argument. The first iteration occurs in the second item of the array, so the first argument is the first item of the array, and the second argument is the second item of the array.
-
Reduce () : start at the first item of the array and iterate to the end;
-
ReduceRight (fn(Prev, cur), defaultPrev): Perform in pairs, and prev is the return value of the last reduction function
- When the incoming
defaultPrev
, start from the first term; - When not passed in, the second item
// Use reduce() to find the sum of all values in the array; var arr = [1.2.3.4.5]; var sum = arr.reduce(function(prev,cur,index,array){ return prev+cur; }) / / 15 Copy the code
- When the incoming
Array deduplication
(1) The for loop is nested, and then the splice method is de-duplicated
Double layer loop, outer layer loop element, inner layer loop compare the value, delete the value of the same value; (Practical in ES5)
function unique(arr){
for(var i=0; i<arr.length; i++){for(var j=i+1; j<arr.length; j++){if(arr[i]==arr[j]){
arr.splice(j,1); j--; }}}return arr;
}
var arr=[1.2.3.3.4];
console.log(unique(arr)); / / = = > 1, 2, 3, 4
Copy the code
(2) Create an array and use indexOf to remove the weight
If the value does not exist, add it to the new array. If the value does not exist, add it to the new array. However, the method “indexOf” is an ES5 method and is not supported below IE8. (Simpler in ES5)
function unique2(arr){
var newArr = []; // A new temporary array
for(var i = 0; i < arr.length; i++){ // Iterate over the current array
// If the ith of the current array is already in the temporary array, skip it; otherwise, push the current item into the temporary array
if (newArr.indexOf(arr[i]) == -1){
newArr.push(arr[i])
};
}
return newArr;
}
Copy the code
(3) ES6 uses Set advanced function to remove weight
function newArr(arr){
return Array.from(new Set(arr))
The // array.from () method converts an array-like object or traversable object into a real Array
}
var arr = [1.1.2.9.6.9.6.3.1.4.5];
console.log(newArr(arr))
// This method does not remove the empty "{}" object
Copy the code
(4) Use the built-in arrayfilter()
;
function unique(arr) {
return arr.filter(function(item, index, arr) {
// Current element, the first index in the original array == current index value, otherwise return current element
return arr.indexOf(item) === index;
});
}
var arr = [1.1.'true'.'true'.true.true.15.15.false.false.undefined.undefined.null.null.NaN.NaN.'NaN'.0.0.'a'.'a', {}, {}];console.log(unique(arr))
/ / (1, "true", true, 15, false, undefined, null, "NaN," 0, "a", {...}, {...}]
Copy the code
(5) Use sort ()
First sort the original array, then compare the adjacent items of the sorted array.
Disadvantages: Sorting changes the original array;
function unique(arr) {
arr = arr.sort(); // the sort() method changes the array;
var newArr = [arr[0]].for (var i = 1; i < arr.length; i++) {
if(arr[i] ! == arr[i -1]) {
newArr.push(arr[i])
}
}
return newArr;
}
Copy the code
Flat array flatern
Will a multi-tiered array [[1, 2], and 3, [4, 5, [6, 7, [8, 9, [10, 11]]]]] in order to an array. Flattening of arrays
function flatern(arr){
const isArray = arr.some(item= > return item instanceof Array)
if(! isArray) {return arr
}
const res = Array.prototype.concat.apply([], arr)
return flatern(res)
}
// Method 2:
const flatten = arr= > {
return arr.reduce((pre, next) = > {
return pre.concat(Array.isArray(next) ? flatten(next) : next); } []); };Copy the code