Message: JS array method is very rich and trivial, learning and using the process always need to repeatedly memory, view the document, but as a JS basis so really should not, we should remember it thoroughly, in-depth understanding of just right. But how? This is exactly the original intention of this article, based on my personal experience summed up, hoping to help people like me confused, solve this headache problem.

Array creation


Arrays can be created in three ways: constructors, literals, and the array.of () method new in ES6.

  • Constructor mode:

    letarr = new Array(); // Create an empty arrayletarr = new Array(10); // Create an array of length 10let arr = new Array('a'); // Create an array containing a string element alet arr = new Array(10, 'a'); // Create an array containing 10 and the string aCopy the code

    The new keyword can be omitted. 2. When passing only one parameter of type number, an array of the specified length is created. You cannot create an array that contains only one element of type number

  • Literal way:

    let arr = [10, 'a']; // Literal, that is, assigning values to arrays directlyCopy the code
  • Array.of() (new in ES6) : The array.of () method converts a set of values (that is, parameters passed in) to an Array. This method compensates for the constructor’s inability to create arrays. It is possible to create an array with only one element of type number.

    letarr = Array.of(3); console.log(arr); // [3] // Parameters can be of various typeslet arr1 = Array.of(1, 'a'.true, null, undefined, {name: "zhangsan"} [45]); console.log(arr1); / / [1,'a'.true, null, undefined, { name: 'zhangsan'}, [45]]Copy the code

Array detection


Two more accurate detection methods:

  • Using the Object’s toString method: Object. The prototype. ToString. Call ([]) = = = “[Object Array]”. // true
  • Array.isArray():

    Array.isArray([1, 2, 3]); // true

Array properties


  • Length attribute:

    Function:
    • Sets or returns the length of an array
    • Can be used to add and remove array items
    letarr = [1, 2]; arr.length = 1; console.log(arr); // [1] arr.length = 3; console.log(arr); / / / 1,,Copy the code

Array methods


JavaScript array methods include array prototype methods, constructor methods (new part of ES6) for each method we mainly understand four aspects: function, parameter, return value, whether the original array changes (a). The prototype approach

  1. Push () : Adds one or more parameters to the end of an array: ele1[, ele2[,…[, elen]] Return value: The length of the array changes after the addition of elements

    let arr = [1, 2, 3];
    let temp = arr.push('a'.'b'); console.log(arr, temp); / / [1, 2, 3,'a'.'b'5]Copy the code
  2. Pop (): Action: Delete last item of array parameter: None Returned value: The item to be deleted does the original array change: Yes

    let arr = [1, 2, 3];
    lettemp = arr.pop(); console.log(arr, temp); 3 / / [1, 2]Copy the code
  3. Unshift (): Effect: Adds one or more parameters to the beginning of an array: ele1[, ele2[,…[, elen]] Returned value: Length of array changed after adding elements: Yes

    let arr = [1, 2, 3];
    let temp = arr.unshift('a'.'b'); console.log(arr, temp); / / /'a'.'b', 1, 2, 3] 5
    Copy the code
  4. Shift (): Action: Deletes the first item in the array Parameter: None Returned value: Deletes the item in the array whether the original array changes: Yes

    let arr = [1, 2, 3];  
    lettemp = arr.shift(); console.log(arr, temp); / / [2, 3] 1Copy the code
  5. Parameter: startIndex[, deleteCount[, item1[,…[, itemN]]]] Returned value: Array of items to be deleted Whether the original array is changed: Yes

    letarr = [1, 2, 3]; // Insert elementslet temp = arr.splice(1, 0, 'a'.'b'); // Insert the element at index 1'a'and'b'console.log(arr, temp); / / [1,'a'.'b', 2, 3] [] // Delete elementslettemp1 = arr.splice(1, 2); // Delete two entries console.log(arr, temp1) from position 1 of index 1; // [1, 2, 3] ['a'.'b'] // Replace an elementlet temp2 = arr.splice(1, 1, 'a'); // Replace the element at index 1 with'a'console.log(arr, temp2); / / [1,'a', 3] [2] // Replace multiple elementslet temp3 = arr.splice(0, 2, 'b'.'c'); // Replace the two entries at the beginning of index 0 with 'b' and 'c' console.log(arr, temp3); / / / "b",'c', 3] [1, 'a'] // Delete all items from the position specified by the first argument to the end of the arraylettemp4 = arr.splice(0); // Delete all items console.log(arr, temp4) starting at index 0; / / [] [" b ",'c', 3]
    Copy the code
  6. CopyWithin () copies elements from start to end to other positions in the current array (target starts). This copy replaces elements from the original position (new in ES6).

    • Target: The target location (inclusive) of the copy, that is, the starting position of the element to be replaced
    • Start: The starting position of the element to copy, 0 by default
    • End: The end position of the element to be copied. Default is the last element in the array

    Return value: Copy the array after the replacement whether the original array changes: yes

    letarr = [1, 2, 3, 4, 5]; // replace elements in index 3~4 with elements in index 0~4. Since there are only two positions to replace, replace 4, 5 with 1,2let temp = arr.copyWithin(3);
    console.log(arr, temp); //  [1, 2, 3, 1, 2] [1, 2, 3, 1, 2]
    
    letarr1 = [1, 2, 3, 4, 5]; // Replace elements in index 3~4 with elements in index 2~4. Since there are only two positions to replace, replace 4, 5 with 3, 4lettemp1 = arr1.copyWithin(3, 2); console.log(arr1, temp1); // [1, 2, 3, 3, 4]Copy the code

    Summary: To summarize the above description, the purpose of copyWithin is to copy elements in the range from start to end, and then replace as many elements as possible from target to the end of the array with those elements

  7. Reverse (): Action: Reverse the original array Parameter: None Returned value: Reversed array Whether the original array changes: Yes

    let arr = [1, 2, 3];
    lettemp = arr.reverse(); console.log(arr, temp); // [3, 2, 1] [3, 2, 1]Copy the code
  8. Sort (): function: sort array

    • If the return value of compareFunction is greater than 0, the order of the current comparison items is reversed; otherwise, the order remains unchanged.
    • Parameters may not be passed. By default, they are in the order of Unicode encoding

    Return value: Sorted array whether the original array changes: yes

    // Sort the array from smallest to largestlet arr = [1, 4, 6, 7, 8, 3, 2];
    let temp = arr.sort((a, b) => {
        returna - b; }) console.log(arr, temp); [1, 2, 3, 4, 6, 7, 8] [1, 2, 3, 4, 6, 7, 8] [1, 2, 3, 4, 6, 7, 8] [1, 2, 3, 4, 6, 7, 8let objArr = [{id: 3, name: "lilei"},{id: 1, name: "hanmeimei"},{id: 2, name: "yimi"}];
    letTempArr = objarr.sort ((a, b) => {// Sort the objects in the array in order of their ids from smallest to largestreturn a.id - b.id;
    }); 
    console.log(objArr); //  [{id: 1, name: 'hanmeimei'}, {id: 2, name: 'yimi'}, { id: 3, name: 'lilei' }]
    console.log(tempArr); // [{id: 1, name: 'hanmeimei'}, {id: 2, name: 'yimi'}, { id: 3, name: 'lilei'}]
    Copy the code
  9. Concat (): Concatenates the current array. Array parameters: value1[, value2[,…[, valueN]]

    • The type of the parameter can be any type.
    • Instead of concatenating the elements to the end of the array, the array type concatenates the elements to the end of the array
    • Not passing is equivalent to copying the array

    Return value: Concatenated array whether the original array changes: No

    letArr = [1, 2];let temp = arr.concat('a', {id:1}, ['lilei'.'hanmeimei']); console.log(arr, temp); // [1, 2] [1, 2,'a', { id: 1 }, 'lilei'.'hanmeimei'] // Used to copy arrayslet arr = [1, 2];
    lettemp = arr.concat(); console.log(arr, temp); // [1, 2] [1, 2]Copy the code
  10. slice(): StartIndex [,endIndex] creates a new array based on one or more elements of the current array. no

    let arr = [0, 1, 2, 3, 4];
    letTemp = arr. Slice (1, 3); Console. log(arr, temp); // Return the element console.log(arr, temp) from index 1 (inclusive) to index 3 (not included); // [0, 1, 2, 3, 4] [1, 2] // Used to copy arrayslet arr = [0, 1, 2, 3, 4];
    lettemp = arr.slice(0); // Return all elements from index 0 (inclusive) to the end of the array console.log(arr, temp); // [0, 1, 2, 3, 4] [0, 1, 2, 3, 4]Copy the code
  11. indexOf(): SearchElement [, fromIndex] Return value: searchElement’s index in the array. If no searchElement is found, return -1

    letarr = [1, 2, 3, 4, 5, 6, 2]; // Start at the beginning of the arraylettemp = arr.indexOf(2); console.log(arr, temp); [1, 2, 3, 4, 5, 6, 2letTemp1 = arr. IndexOf (2, 3); // Look back for element 2 console.log(arr, temp1) from index 3(inclusive); // [1, 2, 3, 4, 5, 6, 2] 6Copy the code
  12. lastIndexOf(): SearchElement [, fromIndex] Return value: searchElement’s index in the array. If no searchElement is found, return -1

    letarr = [1, 2, 3, 4, 5, 6, 2]; // Start at the end of the arraylettemp = arr.lastIndexOf(2); console.log(arr, temp); // [1, 2, 3, 4, 5, 6, 2letTemp1 = arr. LastIndexOf (2, 3); // Look forward to element 2 console.log(arr, temp1) from index 3(inclusive); // [1, 2, 3, 4, 5, 6, 2Copy the code
  13. every(): Callback [, thisArg] Returns true if the function returns true for each item in the array. Callback takes three parameters: item(current item),index(current item index), and array(the array object itself) : true or false.

    let arr = [1, 2, 3, 4];
    let temp = arr.every((item, index, array) => {
        returnitem > 2; }); console.log(arr, temp); // [1, 2, 3, 4]falseCallback () {callback (); callback () {callback (); callback () {callback ()let arr = [1, 2, 3, 4];
    let temp = arr.every(function(item, index, array) {
        returnitem > this.id; }, {id: 2}); console.log(arr, temp); // [1, 2, 3, 4]false
    Copy the code
  14. some(): Callback [, thisArg] : callback[, thisArg] : callback[, thisArg] Callback takes three parameters: item(current item),index(current item index), and array(the array object itself) : true or false.

    let arr = [1, 2, 3, 4];
    let temp = arr.some((item, index, array) => {
        returnitem > 2; }); console.log(arr, temp); // [1, 2, 3, 4]true
    Copy the code
  15. filter(): Callback [, thisArg]; callback[, thisArg]; callback[, thisArg]; Callback takes three parameters: item(current item),index(current item index), and array(the array object itself) : The array of items that the function returns true.

    let arr = [1, 2, 3, 4];
    let temp = arr.filter((item, index, array) => {
        returnitem > 2; }); console.log(arr, temp); // [1, 2, 3, 4] [3, 4]Copy the code
  16. map(): Callback [, thisArg]; callback[, thisArg]; callback[, thisArg]; Callback takes three parameters: item(current item),index(current item index), and array(the array object itself) : Whether the array of the result of each call to the function changes: Involves callback and is therefore uncertain, as detailed in the summary of the prototype method below.

    let arr = [1, 2, 3, 4];
    let temp = arr.map((item, index, array) => {
        returnitem * item; }); console.log(arr, temp); // [1, 2, 3, 4] [1, 4, 9, 16]Copy the code
  17. ForEach (): Runs the given function on each item in the array. ThisArg: callback[, thisArg] : callback has three parameters: item(current item),index(current item index), array(array object itself) Callback is involved and therefore uncertain, as detailed in the summary of the prototype method below.

    let arr = [1, 2, 3, 4];
    letTemp = arr.foreach ((item, index, array) => {// There is no return value, but some operations can be performed herereturn item * item;
    });
    console.log(arr, temp); // [ 1, 2, 3, 4 ] undefined
    Copy the code

    Note: forEach cannot prematurely terminate a loop until all items have been iterated, as the for loop does

  18. Callback [, initialValue] : callback[, initialValue] : callback[, initialValue]

    • Callback iterates with four arguments (prev, cur, index, array)
      • A value, before prev (the initialValue | | array first | | the result of the previous iteration)
      • Cur Current iteration item
      • Index Indicates the index of the current iteration item
      • Array The original array for iteration
    • InitialValue The base value of the iteration. The base value is the first item in the array

    Return value: Does the overall iteration result of the original array change after the array iteration: Involves callback and is therefore uncertain, as detailed in the summary of the prototype method below.

    // Array summationlet arr = [1, 2, 3];
    let sum = arr.reduce((prev, cur, index, array) => {
        returnprev + cur; }); console.log(arr, sum); // [1, 2, 3] 6 // Pass an example of initialValue base valuelet sum1 = arr.reduce((prev, cur, index, array) => {
        returnprev + cur; }, 10); // The return value is: 10+1+2+3 console.log(arr, sum1); // [1, 2, 3] 16Copy the code

    Reduce source code implementation:

    Array.prototype.myReduce = function(callback, initialVal){
       let prev = initialVal || this[0]; 
        for(var i = pre ? 0:1; i < this.length; i++){ prev = callback(prev, this[i], i, this); }return prev
    }
    Copy the code
  19. ReduceRight (): Function: Start from the last item of the array and gradually iterate through to the first item, iterating over all the items of the array (ES5 method) parameter: callback[, initialValue]

    • Callback iterates with four arguments (prev, cur, index, array)
      • A value, before prev (the initialValue | | array first | | the result of the previous iteration)
      • Cur Current iteration item
      • Index Indicates the index of the current iteration item
      • Array The original array for iteration
    • InitialValue The base value of the iteration. The base value is the first item in the array

    Return value: Does the overall iteration result of the original array change after the array iteration: Involves callback and is therefore uncertain, as detailed in the summary of the prototype method below.

    // Concatenate string, concatenate array from back to forwardlet arr = ['h'.'e'.'l'.'l'.'o'];
    let str = arr.reduceRight((prev, cur, index, array) => {
        returnprev + cur; }); console.log(arr, str); / / /'h'.'e'.'l'.'l'.'o' ] 'olleh'
    Copy the code
  20. find(): Callback [, thisArg] {forEach, every, map, some, filter: callback[, thisArg];} Callback is involved, so it is uncertain. See the summary of prototype methods below for more details.

    let arr = [1, 2, 3, 4, 5];
    let temp = arr.find((item, index, array) => {
        return item > 2;
    })
    console.log(arr, temp); // [1, 2, 3, 4, 5] 3
    Copy the code
  21. findIndex(): Callback [, thisArg] callback[, thisArg] forEach, every, map, some, filter If it does not, it returns -1 whether the original array has changed: callback is involved, so it is uncertain, as detailed in the summary of the prototype methods below.

    let arr = [1, 2, 3, 4, 5];
    let temp = arr.findIndex((item, index, array) => {
        return item > 2;
    })
    console.log(arr, temp); // [1, 2, 3, 4, 5] 2
    Copy the code
  22. Fill (): fill the array with the specified elements from start(inclusive) to end (exclusive). If there are already elements in the array, replace the (ES6 new) argument: value[, start[, end]] Return value: The filled array is changed or not: Yes

    let arr = [1, 2, 3, 4, 5];
    let temp = arr.fill('a', 2, 4); console.log(arr, temp); / / [1, 2,'a'.'a', 5] [1, 2, 'a'.'a', 5]
    Copy the code
  23. Includes (): determines whether the array contains the specified elements (new in ES7) parameter: searchElement[, fromIndex] Returned value: true or false Whether the original array is changed: No

    let arr = [1, 2, 3, 4, 5];
    let temp = arr.includes(5);
    console.log(arr, temp); // [1, 2, 3, 4, 5] true// This method addresses one of the shortcomings of indexOf looking at elements, namely the error in finding NaNlet arr1 = [NaN, 'a'];
    let temp1 = arr1.includes(NaN);
    let temp2 = arr1.indexOf(NaN);
    console.log(temp1, temp2); // true- 1Copy the code
  24. ToString (), toLocalString(): Function: Calls the toString() method on each item of the array, returning comma-delimited string arguments: None Returned value: Converted string original word set changed: No

    let arr = [1, [1, 2, [4]], {name: "zhangsan"}, 3];
    let temp = arr.toString();
    console.log(arr); [ 1, [ 1, 2, [ 4 ] ], { name: 'zhangsan' }, 3 ] 
    console.log(temp); // '1,1,2,4, [object object], 3'
    Copy the code
  25. Join (): Function: converts an array element to a string (calls toString for each element) and concatenates it with the specified delimiter (defaults to comma). Returns the concatenated string argument: delimiter, defaults to comma (,) Return value: Concatenated string Whether the original array changes: No

    let arr = [1, [1, 2, [4]], {name: "zhangsan"}, 3];
    let temp = arr.join();
    console.log(arr); [ 1, [ 1, 2, [ 4 ] ], { name: 'zhangsan' }, 3 ] 
    console.log(temp); // '1,1,2,4, [object object], 3'// Array summationlet arr1 = [1, 2, 3];
    console.log(eval(arr1.join('+'))); / / 6Copy the code

Summary of prototype method: 1. Array method is nothing more than the array of add, delete, change, search, conversion, iteration. Add, delete, and modify the original array. Search and transform methods that do not involve callback parameters will not change the original array, and those involved will depend on the situation. Iterative methods are also uncertain because they all involve callback parameters. So why are callbacks uncertain?? First, if you operate directly on the original array in callback, the original array will definitely change. Such as:

letArr = [1, 2, 3, 4];letTemp = arr.forEach((item,index,array) => {array[index] *= item; }); console.log(arr,temp); // [1, 4, 9, 16] undefinedCopy the code

If not directly manipulate the original array, but operating item parameter of the callback, if the item is the basic data type is the original corresponding to the elements in the array will not change, if it is a reference type (array, object, function, etc.) change, because the value of the reference type operation, the essence is the value in storage address the content of the operation, The element in the original array corresponding to item is the same reference address as item, so the corresponding element in the original array will change. (If you still don’t understand this, you can look at the implementation of the array method Polyfill.) 2. All indexing methods start at an operation location and end at an outside operation location

(2). Constructor method

  • ArrayLike [, mapFn[, thisArg]] arrayLike[, mapFn[, thisArg]]

    • ArrayLike: array-like objects, which can be nodeList, arguments, strings, iterable objects, etc
    • MapFn: callback function that operates on the transformed array
    • ThisArg: specifies this in mapFun

    If mapFn is not used, the class array does not change. Using mapFn, the results are consistent with the iterative method described above using callback.

    let str = 'hello';
    let temp = Array.from(str);
    console.log(str, temp); // hello [ 'h'.'e'.'l'.'l'.'o' ]
    let temp1 = Array.from(str, (item, index) => {
        return item.toUpperCase();
    });
    console.log(str, temp1); // hello [ 'H'.'E'.'L'.'L'.'O' ]
    Copy the code

    Summary: Array. The from () is equivalent to the Array. The prototype. Slice. The call (the arguments, 0)

Array extension operators (new in ES6)


An array extension operator converts an array to a comma-separated sequence of arguments. A few simple application scenarios:

  1. An array is converted to a sequence of parameters by the extension operator, without applying
    letarr = [1, 2, 3]; // apply math.min. Apply (null, arr) // Extend operator math.min (... arr)Copy the code
  2. Can be used to copy and concatenate arrays
    let arr1 = [2, 3, 4];
    let arr2 = ['a'.'b'.'c']; / / stitching array arr1 and arr2 console. The log ([arr1,... arr2]); / / [2, 3, 4,'a'.'b'.'c']
    Copy the code
  3. Can be used to break up strings into real arrays,
    [...'hello'] / ['h'.'e'.'l'.'l'.'o' ]
    Copy the code

Write in the last


This is a long story, not to repeat the book or official instructions. But to share some learning ideas, so that beginners can faster and more accurate grasp of JavaScript array, so that students stay in the use of the level of understanding it more. Hopefully, the method I’ve described above gives you an idea of JavaScript arrays at a glance, and makes them easier to remember when comparing several aspects of each method.