Preface:
Definition: An array is an ordered collection of values.
JS arrays are untyped, array elements can be of any type, and different elements of the same array may have different types. Each value is called an element (array element), and each element has a position in the array. Array is a common data format in general coding, especially when parsing background data. Each method I have an example, I hope that through the example of the analysis, so that you can have a clearer understanding of the method. In addition, string and object methods through the following 👇, you can help yourself. I hope I can be of some help to you, it will be my great honor!
Last update at 2021,11,03
String – String
Object the object –
Create an array x=[ ]
let a=["333","999"]; Let aa=new Array(4,8,9); Let aaa=new Array(5); Aaa [0]=6; // Assign the 0th aaa to 6 console.log(aaa); // [6,,,,,] console.log(aa); / /,8,9 [4]Copy the code
Access an array elementx.[index]
let a=["333","999"]; let b=a[0]; Let c=a[a.length-1]; Let f=a["1"]===a[1]; // a["1"] is automatically converted to the number 1 console.log(f); // trueCopy the code
Of course, if we access it in the following way, it will be resolved into a continuous operation that returns the last value
The console. The log (5-tetrafluorobenzoic [2] [1, 2]) / / 4Copy the code
Arrays are also a special kind of object, so we can also access them through key-value pairs
let arr9 = [];
arr9.say = 'Hello';
console.log(arr9.say) // Hello
Copy the code
Three, go through the number groupx.forEach(function(item,index,array){})
Es6 writing forEach ((item, index) = > {dosomething... })
let a=["333","999"]; a.forEach(function (item,index,array) { console.log(item,index) }); / / 1 333 0 999Copy the code
Add elements to the end of the arrayx.push(...)
let a=["333","999"]; A.paush (" I am a new element ","666"); console.log(a); / / / "333", "999", "I am a new element", "666"] the console. The log (Amy polumbo ush (" I ", "690"), a. ength, a); / / 6, "333", "666", "I am a new element", "666", "I", "690"] / / return a new array length 6, will perform a Amy polumbo ushCopy the code
5, Delete array at end (only 1)x.pop()
let a=["333","999"]; a.pop(); console.log(a); / / (" 333 "); Return the new array console.log(a.pop(),a); //333 [] // a.pop() will be executed once to return the deleted elementCopy the code
Delete the first element of the arrayx.shift()
let a=["333","999"]; a.shift(); console.log(a); // ["999"] console.log( a.shift()); // "999" // returns the deleted element, without a.hift ()Copy the code
Add to the front of array (header)x.unshift("..." )
let a=["333","999"]; a.unshift("000","888","777"); console.log(a); // ["000","888","777","333","999"] console.log(a.unshift("111"),a.length,a); / / / "111", "000", "888", "777", "333", "999"] / / will perform a a.u nshift, returned array length,Copy the code
Find the index of an element in an arrayindexOf
let a=["333","999"]; let d=a.indexOf("333"); Console.log (d); console.log(d); // 0 let e=a.indexOf("654"); // Return -1 console.log(e); / / 1Copy the code
Array deep copyslice()
, Array.from()
.[...].
Let a=[1,2,8]; let newArray=a.slice(); console.log(newArray); / /,2,8 [1] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the second method: let newArray2 = Array. The from (a); console.log(newArray2); / /,2,8 [1] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the third method: let newArray3 = [a]... console.log(newArray3); / /,2,8 [1]Copy the code
Empty the array
// let arr=[1,2,3,3,4,5]; arr=[]; The console. The log (arr) / / [] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- let arr = [13] 888; arr.length=0; console.log(arr) // []Copy the code
Merge arrays
let arr=[1]; let arr2=[2]; let arr3=[3]; Let arr4 = arr. Concat (arr2, arr3) console. The log (arr4) / / [1, 2, 3] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / this method also can be achieved, Let arr1=[1,2,3]; Let arr2 = (4 and 6); arr1.push.apply(arr1,arr2); console.log(arr1); / / [1, 2, 3, 4, 5, 6] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / ES6 array merge: const arr1 = [' a ', 'b']. const arr2 = ['c']; const arr3 = ['d', 'e']; [...arr1, ...arr2, ...arr3]; // [ 'a', 'b', 'c', 'd', 'e' ]Copy the code
Find the maximum and minimum values in the array
Array1 = [1,2,3,4]; let array2 = Math.max.apply(null,array1); // let array3 = math.min. apply(null,array1); // Minimum console.log(array2,array3); / / 4, 1 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / method 2 let array4 = math.h Max (... array1); // let array5 = math.min (... array1); // Minimum console.log(array4,array5); / / 4, 1Copy the code
Check whether it is an array
IsArray () var a = [0, 1, 2]; console.log(Array.isArray(a)); // true (2) Typeof toStringCopy the code
Due to the lower versionIE
Does not supportES5
, if compatible, usetypeof
As we all know, arrays are special objects, so arrays oftypeof
The result isobject
And becausenull
As a resultobject
, so we need to add a judgment isobject
At the same time to eliminatenull
, exclude pure objects, judge firsta
Isn’t itobject
And,a! ==null
And,toString.call
judgea
Is equal to the[object Array]
let a = [0, 1, 2]; console.log( typeof a ==='object' && a ! ==null && Object.prototype.toString.call(a) ==='[object Array]'); // trueCopy the code
Operations on arrays and other values (“+” is automatically convertedstring
,”-” will automatically change tonumber
)
Console. log([1,2,3] + 6); console.log([1,2,3] + 6); // "1,2,36" console.log([1,2,3] + {}); / / "1, 2, 3 [object object]" the console. The log ([1, 2, 3] + [1, 2, 3]). // "1,2,31,2,3" if the array has only one value, it is converted to a number when multiplied by other values, or 0 console.log([5] -2) // 3 if it is emptyCopy the code
Array deduplication
// ES6 new Set data structure, similar to array, but the elements are unique, Its constructor can accept an array as a parameter to let arr1 =,2,1,2,6,3,5,69,66,7,2,1,4,3,6,8,9663,8 [1] let the set = new set (arr1); The console. The log (set) / /,2,6,3,5,69,66,7,4,8,9663,8 [1]Copy the code
Shuffle the array order
Let arr = [6]; Function upsetArr(arr){return arr.sort(function(){return math.random () -0.5}); } upsetArr(arr) ; // [4, 1, 3, 2, 5, 6]Copy the code
A) create a random number, and then combine it with a random number
Compare, if math.random () -0.5 is true, return the former, otherwise compare the next
17 implement the sum of the array of numbers, ignore the letters.
Let arr = [" a ", 3,4,5,9, "d"); function sum (arr){ let a=0; for(let i=0; i<arr.length; i++){ if(typeof arr[i]==="number"){ a+=arr[i] } } return a; } sum(arr) //21Copy the code
Determine if each value in the array is a number by looping over it, and if so, assign the value to the variable for addition
Eighteen,delete
.splice
Deletes a value specified in an array.
If you use delete to delete the specified index value of the array, the array is changed directly, and the position of the deleted value remains undefined.
Let arr =,2,3,45,5,2 [1]; Log (arr,arr[0]). // [empty,2,3,45,5],undefinedCopy the code
If you want to delete it completely, use the splice() method
Splice (start position, number of deletions, value added), if there is no third value, you can pass only the first two values
Examples of two values:
Let arr =,2,3,45,5,2 [1]; Arr. Splice (0,1) console.log(arr) // [2, 3, 45, 5, 2]Copy the code
Examples of three values:
Let arr =,2,3,45,5,2 [1]; Arr. Splice (0,1,100) console.log(arr) // [100,2, 3, 45, 5, 2]Copy the code
In the 19th,slice()
Intercepts an array, optionally starting and ending positions
Array.slice(begin,end) accepts two parameters, the first is the start position and the second is the end position
Copy the start position to the end position
If end is omitted, slice extracts all the way to the end of the original array.
If end is greater than the length of the array, Slice will extract all the way to the end of the array
Let arr =,2,3,45,5,2 [1]; Let arr1 = arr.slice(0,4) console.log(arr1). // [1, 2, 3, 45]Copy the code
If no arguments are passed in slice() parentheses, all will be truncated, that is, copied
Let arr =,2,3,45,5,2 [1]; let arr1 = arr.slice() console.log(arr1). // [1, 2, 3, 45, 5, 2]Copy the code
Reversing the order of an array, also known as reversing an array
Let arr =,2,3,45,5,2 [1]; arr.reverse() console.log(arr) // [2, 5, 45, 3, 2, 1]Copy the code
The 21st,join()
Splits an array into strings with values in parentheses (without changing the original array)
Let arr =,2,3,45,5,2 [1]; The console. The log (arr. Join (" _ ")); // "1_2_3_45_5_2" console.log(arr); // [1, 2, 3, 45, 5, 2]Copy the code
22,sort()
Sort, sort the values of an array from large to small or from small to large (changing the original array)
Sort sort can only be compared to the one digit, so we extend it to the following method:
Let arr =,2,3,45,5,2 [1]; array=arr.slice(); Arr. Sort (function(a,b){return a-b}) // [1, 2, 2, 3, 5, 45] Console. log(arr) // [1, 2, 2, 3, 5, 45] arr.sort(function(a,b){return b-a}) // [45, 5, 3, 2, 2, 1] console.log(arr) // [45, 5, 3, 2, 2, 1]Copy the code
Of course, sometimes we can not change the original array, so we can try the following method to copy the contents of the required can be:
Let arr =,3,6,8,45,34,90,122,9,0 [1]; let array=arr.slice(); Array. Push (34) the console. The log (arr, array) / /,3,6,8,45,34,90,122,9,0 [1], [1,3,6,8,45,34,90,122,9,0,34]Copy the code
Array.protype.slice.call(arr,n,m) returns a new Array (without changing the original Array)
Parameters (front package, not back) :
Arr: truncated array n: truncated start position m: truncated end position
The slice.call() method returns a truncated array, using a new method called 🌰.
1. Truncate backwards. The second argument 2 refers to the given truncated position. Delete the element before the current position and return the array copy containing the second argument. Let arr =,2,5,3,6 [1]; The console. The log (Array) prototype. Slice. Call (arr, 2)) / / 2,3,6 [5]. Let arr = [1,2,5,3,6]; let arr = [1,2,5,3,6]; The console. The log (Array) prototype. Slice. Call (arr, 2, 4)) / / [5]Copy the code
An iterative method in an arrayfilter()
.every()
.forEach()
.map()
.some()
.reduce
Filter () : Returns an array of items that return true by running the given function on each item in the array.
Every () : Runs the given function on each item in the array, and returns true if the function returns true for each item.
ForEach () : Runs the given function on each item in the array. This method returns no value.
Map () : Runs the given function on each item in the array, returning an array of the results of each function call.
Some () : Runs the given function on each item in the array, returning true if the function returns true for any item.
Array iteration methodfilter()
A filter returns an array that meets certain criteria, returns a new array, does not change the original array, and can filter false values.
array.filter(function(item,index,array){
})
Copy the code
The filter callback takes three arguments: the current index element, the index, and the original array
item
: Current index elementindex
Index:array
: the original array
Let arr =,3,6,8,45,34,90,122,9,0 [1]; Let array = arr.filter(function(element){return element>10}) console.log(array) [45, 34,90,122] console.log(arr) [1,3,6,8,45,34,90,122,9,0]Copy the code
We can use this function to remove unwanted elements and filter out false values while iterating through the array.
const compact = arr=> arr.filter(Boolean)
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]) // [1, 2, 3, "a", "s", 34]
Copy the code
About this filter fake, in many tool libraries have their own methods to deal with, we on a library method andfilter
Do a comparison, see the specific execution efficiency (serious face).
Function lodashCompact(array) {var index = -1, length = array == null? 0 : array.length, resIndex = 0, result = []; console.time("lodashCompact"); while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value } } console.timeEnd("lodashCompact"); return result; Function test() {lodashCompact(arr); Function test2() {console.time("filter time ") const compacts = arr => arr.filter(Boolean) Console. timeEnd("filter time totals ")}Copy the code
The calculation above is pure execution time,filter
Far more than about 7.6 times, recommended usefilter
!
Array iteration methodevery()
It is used to determine whether the values in an array conform to certain criteria. Each value must be true to return true. Otherwise return false.
Let arr =,2,3,4,5,4,3,2,1 [1]; let everyResult = arr.every(function(item, index, array){ return (item > 2); }); // Check whether all values in the array are greater than 2. If all values are greater than 2, return true, otherwise return false. Console. log(everyResult) //falseCopy the code
Array iteration methodforEach()
Loop over an array, running a given function on each item in the array. This method returns no value.
Let arr =,3,6,8,45,34,90,122,9,0 [1]; arr.forEach(function(item,index,array){ console.log(item,index,array) }) /* 0 1 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 1 3 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 2 6 (10) [1, 3, 6, 8, 8, 45, 34, 90, 122, 9, 0] 3 8 (10) [1, 3, 6, 8, 45, 3. [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 4. [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 5. 0] 6 90 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 7 122 (10) [1, 3, 6, 6, 9, 0] 8 9 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 9 0 0] (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] * /Copy the code
Array iteration methodmap()
Loop through an array, running a given function on each item in the array and returning the result of each function call to form a new array.
Iterate over the array, returning a new array
array.map(function(item,index,array){
})
Copy the code
The map callback takes three arguments: the current index element, the index, and the original array
item
: Current index elementindex
Index:array
: the original array
[1, 2, 3].map(v => v + 1) // -> [2, 3, 4]
Copy the code
Let arr =,3,6,8,45,34,90,122,9,0 [1]; arr.map(function(item,index,array){ console.log(index,item,array) }) /* 0 1 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 1 3 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 2 6 (10) [1, 3, 6, 8, 8, 45, 34, 90, 122, 9, 0] 3 8 (10) [1, 3, 6, 8, 45, 3. [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 4. [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 5. 0] 6 90 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] 7 122 (10) [1, 3, 6, 6, 9, 0] 8 9 (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 9 0 0] (10) [1, 3, 6, 8, 45, 34, 90, 122, 9, 0] * /Copy the code
5. Array iteration methodssome()
(Runs the given function on each item in the array, returning true if the function returns true for any item.)
Let Numbers =,2,3,4,5,4,3,2,1 [1]; let someResult = numbers.some(function(item, index, array){ return (item > 2); }); // Return true console.log(someResult) as long as one of them returns true; // trueCopy the code
Vi.Reduce merge: Iterate over all the values in the array, returning a final conditionally computed value.
reduce:
Method executes a Reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value. Perform reduction, sum, sum, and average
The reducer function receives four parameters: Accumulator (ACC) (Accumulator) Current Value (CUR) (Current Value) Current Index (IDX) (Current Index) The Index starts from 1 by default. Optional Source Array (SRC) (Source Array) This parameter is optional Array.reduce((Accumulator,Value,Index,Array)=>{ //dosomething }Copy the code
Let values = [1, 2, 3, 4, 5]; let sum = reduce(function(prev, cur, index, array){ return prev + cur; }); Prev = 1; cur = 2; prev = 1; The second time, prev is 3 (the result of 1 plus 2) and cur is 3 (the third item in the array). This process continues until each item in the array has been accessed and the result is returned. // Returns the sum of all the values in the array through the loopCopy the code
sum
Let arr =,2,4,6,34,66 [1]; Let res = arr. Reduce ((tap, item, index) = > {the console. The log (` first ${index} : ${tap} + ${item} `); Return tap+item}) // 1st time :1+2 // 2nd time :3+4 // 3rd time :7+6 // 4th time :13+34 // 5th time :47+66 console.log(res) // 113Copy the code
averaging
Let arr =,2,4,6,34,66 [1]; let res = arr.reduce((tap,item,index)=>{ if(index! ==arr.length-1){ return tap+item }else{ return tap/(arr.length) } }); The console. The log (res) / / 7.833333333333333Copy the code
reduceRight:
Let values = [1, 2, 3, 4, 5]; let sum = reduceRight(function(prev, cur, index, array){ return prev + cur; }); // For the first time, prev is 5 and cur is 4. The second time, prev is 9 (the result of 5 plus 4) and cur is 3 (the third item in the array). This process continues until each item in the array has been accessed and the result is returned. // Returns the sum of all the values in the array through the loopCopy the code
In the ES6find
: Finds the first value in the array that matches the condition.
1. If an element matching the condition is found in the array, the element matching the condition is returned.
2. Return undefined if no element matches the condition.
Note: find() is not executed for an empty array.
Note: find() does not change the original value of the array.
Var arr =,2,3,4,5,6,7 [1]; Var ar = arr. Find ((elem) = > {return elem > 5}) / / 6 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var arr =,2,3,4,5,6,7 [1]; var ar = arr.find((elem)=>{ return elem>10 }) // undefinedCopy the code
The array. from: method in ES6 is used to convert two classes of objects into real arrays
The array. from method is used to convert two types of objects into true arrays: array-like objects and iterable objects (including the new ES6 data structures Set and Map).
let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; Var arr1 = [].slice.call(arrayLike); / / / 'a', 'b', 'c'] / / written ES6 let arr2 = Array. The from (arrayLike); // ['a', 'b', 'c']Copy the code
If the argument is a real Array, array. from returns a new Array that looks exactly like it.
Array.from([1, 2, 3]); / / [1, 2, 3]Copy the code
Array.from can also take a second argument, similar to the map method of arrays, that is used to process each element and place the value in the returned Array.
Array.from(arrayLike, x => x * x); From (arrayLike).map(x => x * x); // Array.from([1, 2, 3], (x) => x * x); / / [1, 4, 9]Copy the code
The following example converts a member of an array whose Boolean value is false to 0.
Array.from([1, , 2, , 3], (n) => n || 0) // [1, 0, 2, 0, 3]
Copy the code
Another example is to return various types of data.
function typesOf () {
return Array.from(arguments, value => typeof value);
}
typesOf(null, [], NaN); // ['object', 'object', 'number']
Copy the code
Array.prototype.flat() in ES6 is used to “flatline” nested arrays into one-dimensional arrays.
This method returns a new array with no effect on the original data.
[1, 2, [3, 4]].flat(); [1, 2, 3, 4] // The flat() method takes the members of the subarray and adds them to their original positions.Copy the code
Flat () “flattens” only one layer by default. If you want to “flatten” a nested array of multiple layers, you can write the argument to the flat() method as an integer representing the number of layers you want to flatten, which defaults to 1.
[1, 2, [3, [4, 5]]].flat(); // [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2); // [1, 2, 3, 4, 5]
Copy the code
In the code above, flat() takes 2 to “flatten” the two layers of nested arrays. If you don’t know how many layers are nested, you need to convert them to a one-dimensional array using the Infinity keyword.
[1, [2, [3]]].flat(Infinity); / / [1, 2, 3]Copy the code
If the array is empty, the flat() method skips the empty.
[1, 2, , 4, 5].flat(); // [1, 2, 4, 5]
Copy the code
Null value in ES6
ES5’s treatment of empty seats is already quite inconsistent, mostly ignoring empty seats.
ForEach (), filter(), reduce(), every() and some() all skip empty Spaces.
Map () skips the empty space but keeps the value
Join () and toString() treat empty Spaces as undefined, while undefined and null are treated as empty strings.
/ / the forEach method [, 'a'] forEach ((x, I) = > console. The log (I)); / / 1 / / filter method (' a ', 'b'), a filter (x = > true) / / [' a ', 'b'] / / every method [, 'a']. Every (x = > x = = = 'a') / / true / / reduce method [1, 2]. The reduce (x, y) = > (x + y) / / 3 / / some methods [, 'a']. Some (x = > x! = = 'a') / / false / / map method [, 'a'] map / / (x = > 1) [1] / / join method [, 'a', undefined, null]. Join (' # ') / / "# # #" / / toString method [,'a',undefined,null].toString() // ",a,,"Copy the code
ES6 explicitly converts empty space to undefined.
Reference: Ruan Yifeng teacher’s ES6
Author: sunny day DE rain Source: https://juejin.im/post/6844903512493539341 all rights reserved, welcome to retain the original link reproduced:)Copy the code
If you are interested in my article or have some suggestions for me to listen to 👂, you can also add wechat oh!
If the pro feel my article is good, you can add attention to oh!
Finally, I wish you all the best! - Rookie ChristineCopy the code