JS foundation # day 8

Posted by vladNz on Thu, 23 Dec 2021 05:02:39 +0100

catalogue

1, Create array

new create array

Create a literal array

2, Common methods of array

3, Traversal array

4, call() and apply() of the function

5, arguments

1, Create array

new create array

    // Create an array
    var arr = new Array();
    // 1. When using typeof to check an array, Object will be returned
    console.log(typeof arr); // Object

    // 2. Add element syntax to array: array [index] = value index starts from 0
    arr[0] = 10;
    arr[1] = 21;
    arr[2] = 32;
    // arr[5] = 44;
    console.log(arr); //  [10, 21, 32]
    
    // 3. Read the elements in the array syntax: array [index]
    console.log(arr[1]); // 21 read the position with index 1
    console.log(arr[3]); // undefined will be returned when reading the location where the index does not exist
    
    // 4. Get array length syntax: array length 
    console.log(arr.length); // 3

    // 5.1 for continuous arrays, the length (number of elements) of the array can be obtained by using length
    // 5.2 for discontinuous arrays, using length will get the maximum index of the array + 1

    // 6. Modify length
    // 6.1 if the modified length is greater than the original length, the extra part will be empty
    // arr.lenght = 6;
    // console.log(arr);
    // 6.2 if the modified length is less than the original length, the extra elements will be deleted
    // arr.length = 2
    // console.log(arr);   [10, 21]
    
    // 7. Use length as the index to add an element to the last position of the array. Syntax: array [array. Length] = element
    arr[arr.length] = 33;
    arr[arr.length] = 44;
    console.log(arr); // [10, 21, 32, 33, 44]

    // 8.1 when using the constructor to create an array, you can also add elements at the same time. The elements to be added are passed as parameters of the constructor, and the elements are separated
    var arr1 = new Array(1, 2, 3, 4, 5);
    console.log(arr1); //  [1, 2, 3, 4, 5]

    // 8.2 use the constructor to create an object. If there is only one element n in it, it means that an array with length n is created
    var arr2 = new Array(10);
    console.log(arr2.length); // 10

Create a literal array

    // 1. Create literal array: directly add elements when creating. The elements in the array can be any data type
    var arr = ['Xiao Li', 2, 3, 4, true, {name: 'koko'}, function() {}];
    console.log(arr); // ["Xiao Li", 2, 3, 4, true, {...}, ƒ]
    
    // 2. Multidimensional array: array is placed in the array
    var arr1 = [[1, 2, 3], [4, 5, 6], [7,8]];
    console.log(arr1); // [Array(3), Array(3), Array(3)]
    console.log(arr1[1][1]); // 5

2, Common methods of array

common methodinterpretation
push();

Add one or more elements to the end of the array and return the new length of the array as the return value

pop();

Deletes the last element of the array and returns the deleted element as a return value

unshift();

Add one or more elements to the beginning of the array and return the new length of the array as the return value

shift();

Deletes the first element of the array and returns the deleted element as a return value

forEach()

Traversal array, only supports browsers above IE8

slice();

It is used to extract the specified element from the array without changing the original array

splice();

Deleting / inserting / replacing elements will affect the original array

concat();

Connect two or more arrays and return the new array without affecting the original array

join();

Convert the array to a string and return the converted String as the result, which will not affect the original array

reverse();

Used to invert the array, the original array will be modified directly

sort();

It is used to sort the elements in the array. By default, it will be sorted according to Unicode encoding, which will affect the original array

1.push();  pop();  unshift();  shift();

    // Create an array 
    var arr = [1, 2, 3, 4];
    // 1.push();  This method can add one or more elements to the end of the array and return the new length of the array as the return value
    var re = arr.push(23, 45);
    console.log(arr); // [1, 2, 3, 4, 23, 45]
    console.log(re); // 6
    
    // 2.pop();  This method can delete the last element of the array and return the deleted element as a return value
    var res = arr.pop();
    console.log(arr); // [1, 2, 3, 4, 23]
    console.log(res); // 45
    
    // 3.unshift();  Add one or more elements to the beginning of the array and return the new length of the array as the return value
    // After the element is inserted forward, the indexes of other elements will be adjusted in turn
    var resu = arr.unshift('Jade Hare', 'White horse');
    console.log(arr); // ["Jade Rabbit", "white horse", 1, 2, 3, 4, 23]
    console.log(resu); // 7

    // 4.arr.shift();  You can delete the first element of the array and return the deleted element as a return value
    var result = arr.shift();
    console.log(arr); // ["white horse", 1, 2, 3, 4, 23]
    console.log(result); // Jade Hare

2.slice(); It can be used to extract specified elements from the array. This method will not change the original array, but encapsulate the intercepted elements into a new array and return

Parameters:

(1) the index of the interception start position, including the start index

(2) the index of the position where the interception ends, excluding the end index

  • The second parameter can be omitted without writing. At this time, all elements from the beginning of the index will be intercepted
  • An index can pass a negative value. If a negative value is passed, it is calculated from back to front
    var arr = [1, 2, 3, 4, 5, 6];
    var re = arr.slice(1, 3);
    console.log(re); // [2, 3]
    re = arr.slice(1, -1);
    console.log(re); //  [2, 3, 4, 5]

3.splice(); Delete / insert / replace elements. Using splice() will affect the original array, delete the specified elements from the original array, and return the deleted elements as return values

Parameters:

(1) the first indicates the index of the start position

(2) the second indicates the number of deleted items,

(3) for the third and later, you can pass some new elements, which will be automatically inserted in front of the start position index

  // 1. Delete element
  arr = [1, 2, 3, 4, 5, 6, 7];
  re = arr.splice(1, 3);
  console.log(arr); // [1, 5, 6, 7]
  console.log(re); //  [2, 3, 4]

  // 2. Replace elements
  arr = [1, 2, 3, 4, 5, 6, 7];
  arr.splice(1, 2, 'Bajie', 'name of a fictitious monkey with supernatural powers');
  console.log(arr);  // [1, "Eight Precepts", "Wukong", 4, 5, 6, 7]

  // 3. Insert element: if the deleted quantity is 0, the element is added to the original one
  arr = [1, 2, 3, 4, 5, 6, 7];
  arr.splice(1, 0, 'buddhist monk', 'Xiao Hong');
  console.log(arr); // [1, "monk", "little red", 2, 3, 4, 5, 6, 7]

4.concat() can connect two or more arrays and return the new array. This method will not affect the original array

    var arr1 = ['name of a fictitious monkey with supernatural powers', 'Bajie', 'buddhist monk'];
    var arr2 = ['lili', 'koko', 'nacy'];
    var arr3 = ['shanhaiching', 'Journey to the West', 'Water Margin'];
    var arr = arr1.concat(arr2); // Join two arrays
    console.log(arr); // ["Wukong", "Bajie", "monk", "lili", "koko", "nacy"]

    var arr0 = arr1.concat(arr2, arr3, 'Ox demon king'); // Connecting three arrays can pass not only arrays but also elements
    console.log(arr0); // ["Wukong", "Bajie", "monk", "lili", "koko", "nacy", "Shanhaijing", "journey to the west", "outlaws of the marsh", "ox demon king"]

5.join(); This method can convert the array to a string

  • This method does not affect the original array, but returns the converted String as the result
  • In join(), you can specify a string as a parameter. This string will become the connector of the elements in the array. If you do not specify a connector, it will be used by default as the connector.
    arr1 = ['name of a fictitious monkey with supernatural powers', 'Bajie', 'buddhist monk'];
    var re = arr1.join(', '); 
    console.log(re); // Wukong, Bajie, monk

6.reverse(); This method is used to invert the array. This method will directly modify the original array

    arr1 = ['name of a fictitious monkey with supernatural powers', 'Bajie', 'buddhist monk'];
    arr1.reverse();
    console.log(arr1); // ["monk", "Bajie", "Wukong"]

7.sort(); It can be used to sort the elements in the array and affect the original array. By default, it will be sorted according to Unicode encoding

    arr = [2, 1, 5, 3, 9];
    arr.sort();
    console.log(arr); // [1, 2, 3, 5, 9]

7.1 even for arrays of pure numbers, sorting by sort() will be performed according to Unicode encoding, so wrong results may be obtained when sorting numbers

    arr = [2, 11, 5, 3, 9];
    arr.sort();
    console.log(arr); //  [11, 2, 3, 5, 9]

7.2 you can add a callback function in sort() to specify the sorting rules. The callback function needs to define two formal parameters a and b,

  • a-b: from small to large
  • b-a: in descending order
    arr = [2, 11, 5, 3, 9];
    arr.sort(function(a, b) {
      return a - b;
    })
    console.log(arr); //  [2, 3, 5, 9, 11]

3, Traversal array

1.for loop traversal array

    var arr = [1, 3, 4, 5, 7, 6, 3];
    for (var i = 0; i < arr.length; i++) {
      console.log(arr[i]);  // 1, 3, 4, 5, 7, 6, 3
    }

2.forEach() traverses the array

(1) This method only supports browsers above IE8

(2) This method requires a function as a parameter. Functions like this, which are created by us but not called by us, are called callback functions

(3) There are several elements in the array, and the function will be executed several times. Each time, the browser will pass the traversed elements in the form of arguments. We can define formal parameters to read these contents

(4) The browser passes three parameters in the callback function:

  • The first parameter is the element currently being traversed
  • The second parameter is the index of the element currently being traversed
  • The third parameter is the array being traversed
    var arr = [1, 2, 3, 4, 5, 6];
    arr.forEach(function(value, index, obj) {
      // console.log(value);  1 2 3 4 5 6
      // console.log(index); 0 1 2 3 4 5
      console.log(obj); // [1, 2, 3, 4, 5, 6]
    })

[exercise] array de duplication

    var arr = [1, 2, 3, 1, 4, 2, 2, 5, 6, 6, 7]; // After weight removal: [1, 2, 3, 4, 5, 6, 7]
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
      var n = arr[i];
      if (newArr.indexOf(n) == -1) { // Determine whether there is an element in the array. If there is no element, return - 1
        newArr.push(n);
      }
    }
    console.log(newArr); // [1, 2, 3, 4, 5, 6, 7]

4, call() and apply() of the function

1. When calling call() and apply(), you can specify an object as a parameter. At this time, the object will become this when the function is executed

2. The difference between call() and apply():

(1) the call () method can pass the arguments after the object in turn

(2) the apply () method needs to encapsulate the arguments into an array and pass them uniformly

    function fun(a, b) {
      // console.log(this);
      console.log('a = :' + a);
      console.log('b = :' + b);
    }
    
    var obj1 = {
      name: "obj1",
      sing: function() {
        console.log(this);       
      }
    }
    var obj2 = {
      name: "obj2"
    }
    // fun.apply(obj1); {name: "obj1", sing: ƒ} 
    obj1.sing.apply(obj2) // {name: "obj2"}

    // The call() method can pass arguments after the object in turn
    fun.call(obj1, 1, 2);  // a = :1 b = :2

    // The apply() method needs to encapsulate the arguments into an array and pass them uniformly
    fun.apply(obj1, [1, 2]);  // a = :1 b = :2

this:

  • When called as a function, this is always window
  • When called as a method, this is the object that calls the method
  • When called as a constructor, this is the newly created object
  • When using call and apply calls, this is the specified object

5, arguments

1.arguments is a class array object. It can also manipulate data through index or obtain length

2. When calling the function, the arguments we pass will be saved in arguments

3.arguments.length can be used to get the length of the argument

4. Even if we do not define formal parameters, we can use arguments through arguments, which is just troublesome

5. It has an attribute called callee, which corresponds to a function object, that is, the object of the function currently being pointed to

   function fn() {
     console.log(arguments.length);  
     console.log(arguments.callee == fn); // true
   }
   fn(1, 2, 3); // 3