Common methods used in arrays

Application Programming Interface (API)

  • Anything that can be called from the outside to implement a function is an API

The various methods in which arrays can be retrieved.

  • Method.
  • Method argument.
  • Method.
  • Whether the original array has changed.

1. Array.from([value]): Converts a class Array (or Set structure) to an Array.

  • A collection of elements/a collection of nodes is a class array.
  • Arguments is also a class array.
  • A collection of class arrays that we construct ourselves.
  • .

Array.prototype methods can only be called from an Array. If you want them to be called from an Array, you can convert them to an Array.

2. Array.isarray ([value]): Checks whether the current value is an Array. If it is an Array, it returns true, otherwise it is false.

var allNodes = document.querySelectorAll('*'); console.log(allNodes); console.log(Array.isArray(allNodes)); //false var arr = Array.from(allNodes); // Convert allNodes to an array. Console.log (arr); console.log(Array.isArray(arr)); //trueCopy the code

The result is:

3. Push: insert the contents at the end of the array. Argument: the contents to be inserted. Return value: the latest length of the array after the contents are inserted.

var arr = [10, 20, 30]; var res = arr.push('yunduo'); console.log(res, arr); // 4 [10, 20, 30, "yunduo"] res = arr.push('zxt', 100, function () {}, null); console.log(res, arr); / / 8 [10, 20, 30, "yunduo", "ZXT", 100, ƒ (function), null]Copy the code

The result is:

4. Pop: deletes the contents of the last item in the array. The argument is –, and the return value is the contents of the deleted item.

var arr = [10, 20, 30]; var res = arr.pop(); console.log(res, arr); / / 30 [10, 20]Copy the code

The result is:

5. Unshift: inserts contents at the beginning of the array. Arguments :–, and returns the latest length of the array after insertion.

        var arr = [10, 20, 30];
        var res = arr.unshift('yunduo', 100, 200);
        console.log(res, arr); // 6 ['yunduo', 100, 200 , 10, 20, 30] 
Copy the code

The result is:

6. Shift: deletes the first item in the array. Argument :–, returns the item that was deleted, and the original array changes.

var arr = [10, 20, 30]; var res = arr.shift(); console.log(res, arr); 10 [20, 30] / /Copy the code

The result is:

7. Splice (n,m): delete m elements from index n and return them as a new array. The original array is changed.

var arr = [10, 20, 30, 40, 50, 60]; var res = arr.splice(2, 3); console.log(res, arr); / / / 30,40,50,20,60 [10]Copy the code

The result is:

  • If the splice (n, m, x,…). Delete m elements from index n, replace the deleted contents with x and the value passed later, return the deleted part [array], the original array is changed.
var arr = [10, 20, 30, 40, 50, 60]; var res = arr.splice(1, 2, 'hello', 'yunduo', 'javascript'); console.log(res, arr); / / [20, 30] [10, 'hello,' yunduo ', 'javascript', 40, 50, 60]Copy the code

The result is:

  • If the splice (n, 0, x,…). Insert x before index n, return an empty array (without removing anything), the original array changed.
        var arr = [10, 20, 30, 40, 50, 60];
        var res = arr.splice(1, 0, 'hello', 'yunduo');
        console.log(res, arr); // [] [10, "hello", "yunduo", 20, 30, 40, 50, 60] 
Copy the code

The result is:

8. Slice (n,m): start with index n, find index m (not including m), and return the result as a new array, leaving the original array unchanged (array lookup).

  • Slice (n): Finds the end of the array from index n.
  • Slice (0): a shallow clone of the array, which copies the contents of the original array intact to the new array.
var arr = [10, 20, 30, 40, 50, 60]; var res = arr.slice(2, 4); console.log(res, arr); [30, 40] [10, 20, 30, 40, 50, 60]Copy the code

The result is:

9. Concat: Implement array concatenation, parameter is the concatenated array/value, return the concatenated array, the original array unchanged.

        var arr1 = [10, 20, 30];
        var arr2 = [40, 50, 60];
        var res = arr1.concat('yunduo', arr2);
        console.log(res); // [10, 20, 30, "yunduo", 40, 50, 60] 

Copy the code

The result is:

10. ToString: Converts an array to a string (each item in the array is separated by a comma), leaving the original array unchanged.

11. Join (): converts the array to a string using the specified delimiter, leaving the original array unchanged.

var arr = [10, 20, 30]; console.log(arr.toString(), arr); / / "10, 30" [10, 20, 30] the console. The log (arr. Join (' + ')); Var total = 0; // "10+20+30"; for (var i = 0; i < arr.length; i++) { total += arr[i]; } console.log(total); console.log(eval(arr.join('+'))); // Eval can change a string into a JS expressionCopy the code

The result is:

12. IndexOf: Finds the index at the first occurrence of the current item in the array. If there is no such item in the array, -1 is returned.

13. LastIndexOf: Finds the index of the last occurrence of the current item in the array.

var arr = [10, 20, 30, 20, 40]; console.log(arr.indexOf(20)); //1 console.log(arr.lastIndexOf(20)); //3 console.log(arr.indexOf(100)); If (arr.indexof (100) === -1) {console.log(' array does not contain this item '); }Copy the code

The result is:

14.includes: Directly verifies whether the array contains an item. If yes, returns true; otherwise, false.

var arr = [10, 20, 30, 20, 40]; if (! Arr.includes (100)) {console.log(' array does not contain this item '); }Copy the code

The result is:

15. Reverse: To reverse an array so that the original array is changed.

var arr = [1, 3, 5, 2, 3, 7]; var res = arr.reverse(); console.log(res, arr); [7, 3, 2, 5, 3, 1] [7, 3, 2, 5, 3, 1]Copy the code

The result is:

16. Sort: Sort an array. The original array is also changed, but the sort cannot sort by the size of the number after two or more digits.

        var arr = [1, 3, 5, 2, 3, 7];
        arr.sort();
        console.log(arr); //[1, 2, 3, 3, 5, 7]
        
Copy the code

The result is:

Sort is not used in real projects because it cannot sort numbers by size in two or more digits.

arr = [1, 6, 3, 7, 2, 17, 23, 15]; arr.sort(); console.log(arr); //[1, 15, 17, 2, 23, 3, 6, 7] // For two digits or more, sort does not sort by the size of the digits. // It sorts by Unicode (first, first, same, then second...)Copy the code

The result is:

Sort based on two digits and more cannot sort by size, so it can be used in real projects.

var arr = [1, 6, 3, 7, 2, 17, 23, 15]; Arr. sort(function (a, b) {// sort(a, b) {// sort(a, b) { // if the current anonymous function returns a value <=0, Is an exchange after the current item and location (so as to realize sequence), / / @ a - b ascending and descending order / / / / @ b - a return - 1; Return a - b; return a - b; / /}); console.log(arr); // [1, 2, 3, 6, 7, 15, 17, 23]Copy the code

The result is:

Needs: Order each person in descending order of age.

Var arr = [{name: 'zhang' age: 18}, {name: "bill", the age: 35}, {name: 'Cathy' age: 25}]. arr.sort(function (a, b) { return b.age - a.age; }); console.log(arr);Copy the code

The result is:

17. Fill the array.

var arr = new Array(10); // Create an array of length 10, but each item has no content. arr.fill(null); // Null (null).console. log(arr);Copy the code

The result is:

18. Flat: demotes an array from a multi-dimensional array to a 1-dimensional array.

  • Infinity control is reduced directly to a one-dimensional array, leaving the original array unchanged.
         var arr = [
            10,
            20,
            [
                30,
                40,
                [
                    50,
                    60
                ]
            ],
            [
                70,
                80,
                [
                    90,
                    100
                ]
            ]
        ];
        var res = arr.flat(Infinity);
        console.log(res); //[10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 
Copy the code

The result is:

19. ForEach: iterates over each item in the array, passing a callback function with no return value supported, leaving the original array unchanged.

var arr = [10, 20, 30, 40, 50, 60]; For (var I = 0; var I = 0; var I = 0; i < arr.length; I ++) {console.log(' current item :' + arr[I], 'index :' + I); } // Iterate through each item in the array based on "functional programming" : Arr. ForEach (function (item, index) { //item: the item currently traversed //index: the index currently traversed console.log(' current item: '+ item,' index: '+ index); });Copy the code

The result is:

20. Map: Similar to forEach, it iterates through each item in the array and notifying the anonymous callback function to execute (passing the current item/index to the function),

  • The difference is that map supports return values, and the result returned in the callback function replaces the current item in the array (the original array remains unchanged, and the new array is returned).
var arr = [10, 20, 30, 40, 50, 60]; Var res = arr.map(function (item, index) {return item * index; }); console.log(res); // [0, 20, 60, 120, 200, 300]Copy the code

The result is:

21. Filter: Iterates over each item in the array (both item and index).

  • If the callback returns true, we leave this item in. If the callback returns false, we leave it out.
  • The final filter results are returned in accordance with the new array, the original array remains unchanged, “array filter method, to filter out the conditions,”

Filter out the odd numbers in the array.

var arr = [10, 20, 30, 40, 50, 60]; Var res = arr.filter(function (item, index) {return index % 2 === 0; }); console.log(res, arr); / / [10, 30, 50]Copy the code

The result is:

22. Find: Search for the item matching the condition in the array. Once the item matching the condition is found, the traversal ends.

FindIndex: finds the index matching the condition. Once the index matching the condition is found, the traversal is complete.

var arr = [10, 20, 30, 40, 50, 60]; Var res = arr.find(function (item, index) {return index > 2; }); console.log(res); / / 40Copy the code

The result is:

24. If one of the items in the group satisfies the conditions we set, the whole is true, and the other is false.

Every one of them must be true.

        var arr = [10, 20, 30, 40, 50, 60];
        var res = arr.some(function (item, index) {
            return item >= 50;
        });
        console.log(res); //true
        
        res = arr.every(function (item, index) {
            return item >= 50;
        });
        console.log(res); //false 
Copy the code

The result is: