JavaScript: Arrays

array

The old way

① Array. indexOf()

  • Query from front to back, return the index value of the array where the matched element is located, return -1 if no match is found

  • Elements of simple data types are compared by value when they are queried, and elements of complex data types are compared by addresses

  • // Here indexOf and lastIndexOf return the same index value
    var arr = ['one', 'two', 'three', 'four', 'five', 'six'];
    var first = arr. indexOf('four');
    var last = arr. lastIndexOf('four');
    console. log(first); // 3
    console. log(last); // 3
    

② Array. lastIndexOf()

  • Query from back to front, return the index value of the array where the matched element is located, return -1 if no match is found

  • Elements of simple data types are compared by value when they are queried, and elements of complex data types are compared by addresses

  • // Here indexOf and lastIndexOf return the same index value
    var arr = ['one', 'two', 'three', 'four', 'five', 'six'];
    var first = arr. indexOf('four');
    var last = arr. lastIndexOf('four');
    console. log(first); // 3
    console. log(last); // 3
    

③ Array.concat()

  • Returns a new array after splicing two arrays, which can also be used for shallow copy

  • var arr1 = [1,2,3,4,5,6];
    var arr2 = [11,12,13];
    var arr3 = arr1. concat(arr2);
    console.log(arr3); // [1, 2, 3, 4, 5, 6, 11, 12, 13]
    

④ Array. copyWithin(target, start, end)

  • Copy a certain section of the array and replace n elements after the target index, the corresponding elements will be overwritten; the original array will be changed

  • parameter

    • target: target index (required)
    • start: The start index to be copied (optional). If the last two parameters are not passed, it will start from the element at index 0 of the array, intercept the elements from target to the end of the array, and replace them
    • end: the end index to be copied (optional), excluding the end index, if the copied part exceeds the length from the target index to the end of the array, the excess part will not be processed
  • var arr = [1,2,3,4,5,6];
    arr. copyWithin(0);
    console.log(arr); // [1,2,3,4,5,6]
    // Starting from the 3rd element, replace the next 2 elements with elements with array index values from 0 to 1
    arr. copyWithin(2, 0, 2);
    console.log(arr); // [1, 2, 1, 2, 5, 6]
    
    
    var arr2 = ['one', 'two', 'three', 'four', 'five', 'six'];
    arr2. copyWithin(4);
    console.log(arr2); // ["one", "two", "three", "four", "one", "two"]
    

⑤ Array.entries()

  • Returns an iterable object of an array, which contains the key-value pairs (key/value) of the array

  • var arr = [1,2,3];
    var x = arr. entries();
    console.log(x); // Array Iterator {}
    console.log(x.next()); // {value: [0, 1], done: false}
    console.log(x.next()); // {value: [1, 2], done: false}
    console.log(x.next()); // {value: [2, 3], done: false}
    console.log(x.next()); // {value: undefined, done: true}
    

⑥ Array. fill(value, start, end)

  • From the start index to the end index -1, replace with the filling value, directly change the original array

  • parameter

    • target: filling value (required)
    • start: start index to be copied (optional)
    • end: the end index to be copied (optional), not including the end index
  • var arr = [1,2,3,4,5,6];
    // elements from index 0 to 3, replaced by 10
    arr.fill(10,0,4);
    console.log(arr); // [10, 10, 10, 10, 5, 6]
    arr.fill(55);
    console.log(arr); // [55, 55, 55, 55, 55, 55]
    

⑦ Array. join()

  • Pass in a symbol and use it as a connector to concatenate all the elements in the array into a string

  • var arr = [1,2,3,4,5,6];
    var result = arr. join('-');
    console.log(result); // 1-2-3-4-5-6
    

⑧ Array. pop()

  • Delete the last element of the array and change the original array

  • var arr = [1,2,3,4,5,6];
    arr. pop();
    console.log(arr); // [1, 2, 3, 4, 5]
    

⑨ Array. push()

  • Adds a new element to the end of the array, changing the original array

  • var arr = [1,2,3,4,5,6];
    arr. push(10);
    console.log(arr); // [1, 2, 3, 4, 5, 6, 10]
    

⑩Array.reverse()

  • Inverts the entire array, changing the original array

  • var arr = [1,2,3,4,5,6];
    arr. reverse();
    console.log(arr); // [6, 5, 4, 3, 2, 1]
    

⑩① Array. shift()

  • Delete the first element of the array, changing the original array

  • var arr = [1,2,3,4,5,6];
    arr. shift();
    console.log(arr); // [2, 3, 4, 5, 6]
    

⑩② Array.unshift()

  • Add a new element before the first element of the array, changing the original array

  • var arr = [1,2,3,4,5,6];
    arr. unshift(10);
    console.log(arr); // [10, 1, 2, 3, 4, 5, 6]
    

⑩③ Array. slice(start, end)

  • Gets a new array of array slices

  • var arr = [1,2,3,4,5,6];
    var result1 = arr.slice(); // shallow copy array
    var result2 = arr.slice(3); // Get a new array of elements from index 3 to the end
    var result3 = arr.slice(-2); // Get a new array of elements from the end (-1) to -2
    var result4 = arr.slice(1,3); // Get a new array of elements from index 1 to index 2 (not including the end index)
    console.log(result1, result2, result3, result4); // [1, 2, 3, 4, 5, 6] , [4, 5, 6] , [5, 6] , [2, 3]
    

⑩④ Array. sort(function(a,b){})

  • Sort the array forward/reversely, it can be letters or numbers

  • var arr1 = [1,3,4,2,9,6];
    var arr2 = [1,3,4,2,9,6];
    arr1. sort(function(a,b){<!-- -->
        return a - b;
    });
    console.log(arr1); // [1, 2, 3, 4, 6, 9]
    arr2.sort(function(a,b){<!-- -->
        return b - a;
    });
    console.log(arr2); // [9, 6, 4, 3, 2, 1]
    

⑩⑤ Array.splice(start, end)

  • Delete the fragments in the array and change the original array. If the end is not passed, it means all the way to the end

  • var arr = [1,2,3,4,5,6,7,8,9,10];
    arr.splice(-2); // Delete elements from the end (-1) to -2
    console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8]
    arr.splice(0,2); // Starting from index 0, delete two elements backward
    console.log(arr); // [3, 4, 5, 6, 7, 8]
    arr.splice(2); // Starting from index 2, delete all elements behind
    console. log(arr); // [3, 4]
    

⑩⑥ Array.toLocaleString()

  • Concatenate array elements into strings with concatenation according to local rules

  • var arr = [1,2,3,4,5,6];
    var result = arr. toLocaleString();
    console.log(result); // '1,2,3,4,5,6'
    

⑩⑦Array.toString()

  • It is equivalent to calling each element to call the toString method, and then splicing it into a string

  • var arr = [1,2,3,4,5,6];
    var result = arr. toString();
    console.log(result); // '1,2,3,4,5,6'
    

ES6 new method

① Array.keys()

  • Returns the iterator object corresponding to the array

  • var arr = [0,1,2,3,4,5,6];
    var keys = arr. keys();
    console.log(keys); // Array Iterator {}
    for(var item of keys){<!-- -->
        console.log(item); // 0, 1, 2, 3, 4, 5, 6
    }
    

② Array.every()

  • Returns true when all elements in the array meet the criteria

  • var arr = [1,2,3,4,5,6];
    var result = arr.every((value, index, arr)=>{<!-- -->
        return value > 3;
    })
    console. log(result); // false
    

③ Array.some()

  • Returns true when there is only one element in the array that meets the condition

  • var arr = [1,2,3,4,5,6];
    var result = arr.some((value, index, arr)=>{<!-- -->
        return value > 3;
    })
    console. log(result); // true
    

④ Array. filter()

  • Combine the elements that meet the filter conditions into a new array and return

  • var arr = [1,2,3,4,5,6];
    var result = arr. filter((value, index, arr)=>{<!-- -->
        return value > 4;
    })
    console.log(result); // [5, 6]
    

⑤ Array. find()

  • Returns the first eligible element itself (not the index)

  • var arr = [1,2,3,4,5,6];
    var result = arr. find((item, index, arr)=>{<!-- -->
        return item > 2;
    })
    console.log(result); // 3
    

⑥ Array. findIndex()

  • Returns the index of the first element that meets the criteria

  • var arr = [1,2,3,4,5,6];
    var result = arr. findIndex((item, index, arr)=>{<!-- -->
        return item > 2;
    })
    console.log(result); // 2
    

⑦ Array.forEach()

  • Traversing the array, there is no return value (undefined), once started, the loop cannot be stopped halfway (return is not OK, but the current one can be skipped)

  • var arr = [1,2,3,4,5,6];
    var result = arr.forEach((item, index, arr)=>{<!-- -->
        console.log('element value: ' + item + ', index: ' + index + ', current array: ' + arr);
    })
    console.log(result); // undefined
    

⑧ Array. map()

  • Array of maps, each element corresponds to a new value

  • var arr = [1,2,3,4,5,6];
    var result = arr. map((value, index, arr)=>{<!-- -->
        return value + 1;
    });
    console.log(result); // [2, 3, 4, 5, 6, 7]
    

⑨ Array.reduce((pre, cur)=>{}, initValue)

  • It is often used to calculate the sum of array element values, and other usages, such as: deduplication, etc.

  • parameter

    • pre: the value of the last return
    • cur: current element
    • initValue: initial value (ie: the value of pre in the first cycle), if not passed, the cycle starts from the second element, and pre is the first element
  • var arr = [1,2,3,4,5,6];
    var result1 = arr. reduce((pre, cur)=>{<!-- -->
        return pre + cur;
    });
    console.log(result1); // 21
    var result2 = arr. reduce((pre, cur)=>{<!-- -->
        return pre + cur;
    }, 10);
    console.log(result2); // 31
    

⑩Array.reduceRight((pre, cur)=>{}, initValue)

  • It is often used to calculate the sum of array element values (looping from the last item), and some other usages, such as: deduplication, etc.

  • parameter

    • pre: the value of the last return
    • cur: current element
    • initValue: initial value (ie: the value of pre in the first cycle), if not passed, the cycle starts from the second element, and pre is the first element
  • var arr = [1,2,3,4,5,6];
    var result = arr. reduceRight((pre, cur)=>{<!-- -->
        return pre + cur;
    }, 10);
    console. log(result); // 31
    

⑩①Array.values()

  • Returns the iterator object corresponding to the array

  • var arr = [1,2,3,4,5,6];
    var values = arr. values();
    console.log(values); // Array Iterator {}
    for(var item of values){<!-- -->
        console.log(item); // 0, 1, 2, 3, 4, 5, 6
    }
    

Static method

Static method: that is, a method defined on a class that cannot be directly called by an instance object created

① Array.from(array-like, mapping method)

  • ES6 method for converting array-like objects to real arrays

  • parameter:

    • array-like object
      • Array-like objects must have a length attribute, which specifies the length of the array; if there is no length attribute, then the converted array is an empty array
      • The attribute name of an array-like object must be a numeric or string number; if not, the corresponding element after conversion is undefined
    • mapping method (optional)
      • Receive two parameters (item and index), the usage and function are similar to the map method of an array, and map the converted elements once
  • // object type conversion to array
    var arrayLike1 = {<!-- -->
        0: 'tom',
        '3': '18',
        length: 6
    }
    var result1 = Array.from(arrayLike1);
    console.log(result1); // ["tom", undefined, undefined, "18", undefined, undefined]
    
    // set type converted to array
    var arrayLike2 = new Set([1,2,3,4,5]);
    var result2 = Array. from(arrayLike2);
    console.log(result2); // [1, 2, 3, 4, 5]
    
    // convert string to array
    var str = 'hello world';
    var result3 = Array. from(str);
    console.log(result3); // ["h", "e", "l", "l", "o", " ", "w" , "o", "r", "l", "d"]
    
    // array shallow copy
    var arr = [1,2,3,4, {<!-- -->name: 'zs'}]
    var result4 = Array. from(arr);
    console.log(result4); // [1,2,3,4, {name: 'zs'}]
    console.log(result4[4] === arr[4]); // true
    
    // map new array
    var arrayLike5 = {<!-- -->
        0: 'tom',
        '3': '18',
        length: 6
    }
    var result5 = Array.from(arrayLike5, (item, index)=>{<!-- -->
        if(item === undefined) {<!-- -->
            return 'A'
        } else {<!-- -->
            return item; // The rest returns itself, otherwise it returns undefined
        }
    });
    console.log(result5); // ["tom", "A", "A", "18", "A", "A"]
    

② Array.isArray()

  • It is used to judge whether an object is an array, if yes, return true, otherwise return false

  • var arr = [1,2,3,4,5];
    var result = Array.isArray(arr);
    console. log(result); // true
    

③ Array.of()

  • Used to replace new Array() When creating an array, you need to judge a variety of situations (multiple manifestations), pass in different parameters, and get an array with different effects

  • The Array.of() method has only one representation

  • var oldArr1 = new Array();
    var oldArr2 = new Array('3');
    var oldArr3 = new Array(3);
    var oldArr4 = new Array(1,2,3);
    var oldArr5 = new Array(undefined);
    console.log(oldArr1); // []
    console.log(oldArr2); // ["3"]
    console.log(oldArr3); // [empty × 3] or [,,]
    console.log(oldArr4); // [1, 2, 3]
    console.log(oldArr5); // [undefined]
    
    
    var newArr1 = Array.of();
    var newArr2 = Array.of('3');
    var newArr3 = Array.of(3);
    var newArr4 = Array.of(1,2,3);
    var newArr5 = Array.of(undefined);
    console.log(newArr1); // []
    console.log(newArr2); // ["3"]
    console. log(newArr3); // [3]
    console.log(newArr4); // [1, 2, 3]
    console.log(newArr5); // [undefined]