15, Array basis, array method, array sorting

Posted by CoffeeOD on Wed, 12 Jan 2022 08:16:02 +0100

15, Array basis, array method, array sorting

1, Array basis

1.1 three ways to declare arrays

It is recommended to create arrays in the form of array literals

var arr1 = []; //array literal 

// The system's built-in Array constructor declares an Array
var arr2 = new Array(); //Not recommended
var arr3 = Array(); //Not used

All arrays (regardless of the declaration method) inherit array Prototype, under which the methods and properties can be inherited and used.

There are three ways to declare objects: (analogy to array)

It is recommended to create objects in the literal form of objects

var obj1 = {};//Object Literal 

// The system's built-in Object constructor declares objects
var obj2 = new Object();
var obj3 = Object();

All objects inherit object Prototype, under which the methods and properties can be inherited and used.

1.2 an array is a special object

1.2.1 why is an array a special object

Like objects, it is also a key name corresponding to a key value. We use the key name in the array as the subscript of the array element; At the same time, array is also an orderly embodiment of objects.

var arr = [1,2,3,4,5];
// Declare an object as an array
var obj = {
    0: 1,
    1: 2,
    2: 3,
    3: 4,
    4: 5
}
// Print 3
console.log(arr[2]); //3
console.log(obj[2]); //3

1.2.2 what is an array subscript:

Each element in the array corresponds to a position, which is what we call the subscript, or index.

1.2.3 why is the print array [length] undefined?

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

Because the array is equivalent to a special object, it returns undefined when accessing properties that do not exist in the object; When accessing array [length], this element does not exist in the array, so undefined is also returned.

var obj = {
    0: 1,
    1: 2,
    2: 3,
    3: 4,
    4: 5
}
console.log(obj[5]);//undefined

1.2.4 like objects, arrays can be added, modified and queried

var arr = [1,2,3,4,5];
arr[6] = 7; //increase
arr[0] = 10; // change
console.log(arr[0], arr); //check

Leave it for deletion?

1.2.5 create array with new array()

Sparse array: there are null values in the array.

  • When using the built-in constructor to declare an array, the array cannot have null values; Null values after the last comma in the array are ignored.

    var arr1 = new Array( 2, 3, 7, );
    
  • Pass a numeric parameter x to construct an array with length x; This array has elements, but each element is empty, called empty [,].

    var arr2 = new Array(5);
    
  • If a decimal number is passed, an error message will be reported: Invalid array length.

    var arr3 = new Array(5.2);
    
  • Pass in a string and put the string as an element in the array.

    var arr4 = new Array('a');
    

2, ※ array method

The special methods of array are from array Inherited from prototype.

Some methods are static methods from Array, such as Array Isarray() is used to determine whether the value passed is a Array.

Here are 7 methods to modify the original array:

push and unshif

pop and shift

reverse

splice

sort

2.1 ※ push and unshift

Function:

  • push() adds an element at the end of the array
  • unshift() adds an element at the beginning of the array

Return value: the length of the array after the method is executed.

Parameters: multiple or one can be passed:

push(5,6,7) unshift(1)

var arr = [2,3,4];
console.log(arr.push(5,6,7),arr);
console.log(arr.unshift(1),arr);

Implement the push method yourself:

var height = [180, 177];
// Implement the push method yourself
Array.prototype.myPush = function(){
    for(var i = 0; i < arguments.length; i++){
        this[this.length] = arguments[i]; 
        //Who calls it and who this points to, so that all arrays can use this function
    }
    return this.length; //Returns the array length after execution
}
console.log(height.myPush(178, 180), height);

return returns the length of the array after the method is executed.

2.2 ※ pop and shift

Function:

  • pop() cuts the last element of the array
  • shift() cuts the first element of the array

Return value: a bit element to be cut.

Parameter: None

var arr = ['a', 'b', 'c', 'd'];
console.log(arr.pop(), arr);
console.log(arr.shift(), arr);

var height = [180, 177];
var h = height.pop();
console.log(h);

You can use a variable to receive a cut element.

2.3 ※splice

2.3.1 basic use of splice

Function:

  • Delete (cut) the adjacent elements specified in the array;
  • Replace elements (add elements at the deleted position while deleting);
  • Add only elements;

Return value: an array of cut elements.

Parameters: 2+n

The first two parameters mean: the subscript of the start item; Shear length.

The following parameters represent the inserted element.

  • Delete the specified adjacent elements in the array (only 2 parameters are passed in):

    var arr = ['a', 'b', 'c', 'd'];
    console.log(arr.splice(0, 2), arr);
    

  • Replace element (pass in 2+n parameters)

    var arr = ['a', 'b', 'c', 'd'];
    console.log(arr.splice(1,2,'white','rose'), arr);
    

  • Add elements only (pass in 2+n parameters):

    var arr = ['a', 'b', 'c', 'd'];
    console.log(arr.splice(3,0,'pig','dog'), arr); 
    

Summary: both deletion and insertion can be regarded as calculating the cut length from the element of the starting subscript to the previous element, and then changing the array.

2.3.2 how does splice judge the position of elements

The first parameter of splice can be negative

var arr = ['a', 'b', 'c', 'd'];
console.log(arr.splice(-1, 1),arr);

When the array accesses elements, the subscript starts from 0 and is 0, 1, 2... All positive;

The logical process of taking the positive and negative of the subscript in splice:

var arr = ['a', 'b', 'c', 'd'];
function splice(arr, index){
    return index > 0 ? index
                     : index + arr.length;
}
console.log(arr[splice(arr, -1)]); // 'd'
console.log(arr[splice(arr, -2)]); // 'c'

2.4 reverse

Function: invert the array.

Return value: the array in reverse order.

Parameter: None

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

3, Array sorting

3.1 sort

3.1.1 basic usage

Function: sort in ascending order according to ASCII code.

Return value: array after sorting.

Parameter: None

var arr = [8, 7, 9, 5, 1, 2];
var arr2 = ['b', 'z', 'a', 'h', 'j'];
var arr1 = [27, 49, 5, 7];
console.log(arr.sort(),arr);
console.log(arr2.sort(),arr2);
console.log(arr1.sort(),arr1);

When sorting by sort, the number is changed into a string, which is arranged in ascending order according to ASCII code. One by one comparison is made between the previous character and the next character. If the comparison of the previous character has a result, the following characters will not be compared.

※ 3.1.2 user defined array sorting method

Return value:

  1. Negative value, a comes first
  2. Positive value, b first
  3. 0, hold still

Parameters: two parameters a, b; There must be.
a represents the previous element in the array, and b represents the next element in the array.

Comparison method: circularly compare two adjacent values to achieve the effect of bubble sorting.

Sort in ascending order:

var arr = [27, 49, 5, 7];
arr.sort(function(a, b){
    if(a > b){
        return 1;
    }else {
        return -1;
    }
});
console.log(arr);

It can also be abbreviated as:

var arr1 = [27, 49, 5, 7];
arr1.sort(function(a, b){
    return a - b;
});
console.log(arr1);

If a > b, return A-B > 0, that is, return is a positive value.

b is in the front, that is, small values are in the front, and the array is in ascending order.

As long as the logic is consistent, the sorted array is the same.

Note: the company pays attention to the readability of the code, not that the less the code is written, the better.

3.1.2 random sorting

Use the form of a custom array.

Usage: math Random(), randomly returns a number of (0,1) open intervals.

arr.sort(function(a, b) {
    if(Math.random() > 0.5){
        return 1;
    }else {
        return -1;
    }
})
//Abbreviated form
arr.sort(function(a, b) {
    return Math.random() - 0.5;
})
console.log(arr);

If math If random () is greater than 0.5, put this value back, and the custom function of sort return s a positive value.

※ 3.1.3 sort by an attribute of the object in the array

Sort the objects in ascending order according to the num attribute of the objects in the array:

var friends = [
    {
      name: 'rose',
      num: 25
    },
    {
      name: 'jordan',
      num: 45
    },
    {
      name: 'kobe',
      num: 41
    },
];
// Sort the objects in ascending order according to the num attribute of the objects in the array
friends.sort(function(a, b) {
    if(a.num > b.num){
        return 1;
    }else{
        return -1;
    }
});
console.log(friends);

3.1.4 sorting by string length of elements in the array

Sort in ascending order by the length of the element string in the array:

var arr = ['12345,', '1', '123', '14', '1,']; 
arr.sort(function heihei(a, b ) {
    if(a.length > b.length){
        return 1;
    }else{
        return -1;
    }
});
console.log(arr);

Topics: Javascript Front-end