Arrays, functions and objects of JavaScript(2)

Posted by shoutdots on Wed, 19 Jan 2022 15:01:28 +0100

1, Array

Concept of array:
It can store a group of relevant data together and provide convenient access
What is an array:
An array is a collection of data, each of which is called an element. Any type of element can be stored in the array.

//Ordinary variables can only store one value at a time
var num = 10;
//Arrays can store multiple values at a time
var arr = [1,2,3,4,5];

1. Creation method of array

There are two ways to create arrays in JavaScript:

  • Create an array with new
var Array name = new Array();
var arr = new Array();//Create an empty new array 
  • Creating arrays using array literals
//1. Create an empty array using array literal
var Array name = [];
//2. Create an array with initial value using array literal
var Array name = ['Xiaobai','Xiao Hei','chinese rhubarb'];

Declaring an array and assigning values is called array initialization
Any data type can be stored in the array, such as string, number, Boolean value, etc

2. Access array elements

(1) Index of array

Index (subscript): the ordinal number used to access array elements. The array subscript starts from 0
The array can be accessed, set and modify the corresponding array elements through the index. We can obtain the elements in the array in the form of array name [index]. Access here means getting

//Define array
var arr = [1,2,3];
//Gets the second element in the array
alert(arr[1]);//The subscript starts at 0

(2) Traversal array

Traversal: access every element in the array from beginning to end

//Traverse 1,2,3
var arr = [1,2,3];
for(var i = 0; i < 3; i++){
console.log(arr[i]);
}
//Because array index numbers start at 0, i must start at 0

I in the for loop is the counter. When the index number is used, arr[i] is the ith array element of the array element
Array length

  • Use array names Length the number of array elements that can be accessed (array length)
  • The length of the array is the number of elements
  • arr.length dynamically detects the number of array elements

★ find the maximum value in the array:

    //Find the maximum value in the array
    //1. Initialize arr[2,6,1,77,52,25,7]
    //2. Declare the maximum value max. the default maximum value can be the first element in the array
    //3. Traverse the array for to find a value larger than the current max
    //4. If the traversed element is greater than max, store this element in max 
    var arr = [2,6,1,77,52,25,7];
    var max = arr[0];
    for (var i = 0; i <arr.length; i++){
      if(arr[i]>max){
        max = arr[i];
      }
    }
    console. log(max);

(3) New element in array

You can add array elements by modifying the length and index number
1. You can modify the length
var arr = [1,2,3 ];
arr.length = 5; // Increase the number of elements in the array to 5

  • You can achieve the purpose of array expansion by modifying the length
  • The length attribute is readable and writable

2. Modify index number
var arr = [1,2,3 ];
arr[3] = 'pink;'// Append array elements

  • Do not directly assign a value to the array name, otherwise the previous data will be overwritten

★ flip array:

 //Flip array [1,2,3,4,5] - [5,4,3,2,1]
    var arr = [1, 2, 3, 4, 5];
    var i = 0;
    var j = arr.length - 1;
    while (i<=j){
      var tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
      i++;
      j--;
    }
    console.log(arr);

★ filter array:

//Select the elements greater than or equal to 10 in the array [2,0,6,1,77,0,52,0,25,7] and put them into the new array
  //  Method 1:
   var arr = [2,0,6,1,77,0,52,0,25,7];
   var newArr = [];
   var j = 0;
   for (var i = 0; i < arr.length; i++){
     if(arr[i] > 10){
      //  The index number of the new array must be incremented from 0
       newArr[j] = arr[i];
       j++;
     }
   } 
   console.log(newArr);
  //  Method 2
  var arr = [2,0,6,1,77,0,52,0,25,7];
   var newArr = [];
  //  Just started newarr Length is 0
   for (var i = 0; i < arr.length; i++){
     if(arr[i] > 10){
      //  The index number of the new array must be incremented from 0
       newArr[newArr.length] = arr[i];
     }
   } 
   console.log(newArr);

★ array de duplication:

 //Remove 0 from array [2,0,6,1,77,0,52,0,25,7] to form a new array without 0
  var arr = [2,0,6,1,77,0,52,0,25,7];
  var newArr = [];
  for (var i = 0; i < arr.length; i++){
   if(arr[i] != 0){
     newArr[newArr.length] = arr[i];
   }
  }
  console.log(newArr);

★ bubble sorting:

// Bubble sorting
    var arr = [1,2,3,4,5];
    for (var i = 1; i <= arr.length - 1; i++) {//Cycle four times in turn
      for (var j = 0; j <= arr.length - i - 1; j++) {//Each element is compared 4 times, and those that have been compared are no longer compared
        if (arr[j] > arr[j + 1]) {//The previous element is greater than the latter
          var temp = arr[j];//Exchange with intermediate variables
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
        }
      }
    }
    console.log(arr);

2, Functions

A function is a piece of code that encapsulates a block of code that can be called repeatedly. The purpose is to reuse a large amount of code

1. Use of functions

1. Declaration function
Function function name (){
Function body
}

♦ Function declares that the keywords of the function are all lowercase
♦ A function is to do something. The name of a function is usually a verb
♦ The function must be called, otherwise it cannot be executed

2. Call function
Function name ()

♦ Calling a function must be parenthesized

2. Two declaration methods of function:

1. Use function keywords to customize functions (named functions)
Function function name (){
Function body
}
function();
2. Function expression (anonymous function)
var variable name = function() {};

var fun = function(are) {
	console.log('I'm a function expression');
	console.log(are);
	}
	fun('I am pretty');

be careful:
(1) fun is a variable name, not a function name
(2) Function expressions are declared in the same way as variables, except that values are stored in variables
(3) Function expressions can also pass parameters

Function encapsulation: it is to encapsulate one or more functions through functions, and only provide a simple interface

3. Parameters of function

You can use the parameters of the function to repeat different codes
Function function name (formal parameter 1, formal parameter 2,...) {} / / in the parentheses of the declared function are formal parameters (formal parameters)
Function name (argument 1, argument 2,...)// Actual parameters
A formal parameter receives an argument and is equivalent to a variable

Function of parameters: some values cannot be fixed inside the function. We can pass different values through parameters when calling the function
Formal parameters can be regarded as undeclared variables
The number of formal and actual parameters does not match:

  • If the number of arguments is more than the number of formal parameters, the number of formal parameters will be obtained
  • If the number of arguments is less than the number of formal parameters, more formal parameters are defined as undefined, and the final result is NaN

Parameter summary of function:

4. Return value of function

Format of return value of function:
Function function name (){
return the result to be returned;
}
Function name ();
As long as the function encounters return, it returns the following results to the function caller
Function name () = result after return

★ practice of function return value:

// Using function to find the largest number in the array [5,2,99101,67,77]
    function getMax(arr){
      // First, define a new array Max [] and put it into the 0th element of the arr array
      var max = arr[0];
      // Because Max already points to element 0, i points to the first element
      for ( var i = 1; i < arr.length; i++){
        if(arr[i] > max){
          max = arr[i];
        }
      }
      return max;
    }
    // Function name () = value after return
    var re = getMax([5,2,99,101,67,77]);
    console.log(re);
 // Using function to find the second largest number in the array [5,2,99101,67,77]
    function getMax(arr) {
      var max = 0;
      var max2 = 0;
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] > max) {
          max = arr[i];
        }
        if (arr[i] < max && arr[i] > max2) {
          max2 = arr[i]
        }
      }

      return max2;
    }
    // Function name () = value after return
    var re = getMax([5, 2, 99, 101, 67, 77]);
    console.log(re);

Precautions for function return value
1.return terminates the function. The following code will not be executed
2.return can only return one value. The returned result is the last value

3. If the function does not return, the returned result is undefined
Differences between the three:

5. Use of arguments

When we are not sure how many parameters are passed, we can use argument to get them. In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object in which all arguments passed are stored.

arguments is displayed as a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics:

  • With length attribute
  • Store data by index
  • push,pop and other methods without array

Function use cases:

//  Flip any array with function
    function flit(arr) {
      var arr2 = [];
      for (var i = arr.length - 1; i >= 0; i--) {
        arr2[arr2.length] = arr[i];
      }
      return arr2;
    }
    var re = flit([5, 6, 7, 8]);
    console.log(re);

 //  Using function bubble sorting from small to large
    function sort(arr) {
      for (var i = 1; i <= arr.length - 1; i++) {
        for (var j = 0; j <= arr.length - i - 1; j++) {
          if (arr[j] > arr[j + 1]) {
            var tep = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = tep;
          }
        }
      }
      return arr;
    }
    var re = sort([68, 11, 6, 34, 25]);
    console.log(re);
//  Enter a year to determine whether it is a leap year
    function getYear(year) {
      var flag = false;
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        flag = true;
      } 
        return flag;
    }
    console.log(getYear(2004));
 //The user enters a year to determine whether it is a leap year. Here, calls between functions are used
    function outputYear() {
      var year = prompt('Please enter the year');
      if (getYear(year)) {
        alert('It's a leap year');
      } else {
        alert('Not a leap year');
      }
    }
    outputYear();
    function getYear(year) {
      var flag = false;
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        flag = true;
      }
      return flag;
    }
    console.log(getYear(2004));

3, Scope

What is scope:
The purpose is to improve the reliability of the program and, more importantly, to reduce naming conflicts
Before the scope (es6) of js: global scope local scope

Global scope: the entire script tag or a separate js file
Note: if there is no declaration inside the function, the directly assigned variable is also a global variable
Local scope (function scope): it is the local scope inside the function. The name of this code only plays an effect and role inside the function
Note: the formal parameters of a function can also be regarded as local variables

<script>
    // global scope
    var num = 10;
    function fn() {
     // Local scope
     	var num = 20;
    }
  </script>

From the implementation effect:
Global variable: it can be used anywhere. It will be destroyed only when the browser is closed, so it takes up more memory
Local variable: it is only used inside the function and will be initialized when its code block is executed; The contemporary code block will be destroyed after running, so it saves more memory space

Scope chain:
The internal function accesses the variables of the external function and uses the chain search method to determine which value to take. This structure is called the scope chain proximity principle
Stand on the target and start. Look out layer by layer

4, Pre analysis

The JavaScript parser runs JavaScript code in two steps: pre parsing and code execution
Pre resolution:
The pre parsing js engine will promote all var and function s in js to the front of the current scope
Code execution:
Execute from top to bottom according to the code writing order
Pre parsing is divided into:
Variable pre parsing (variable promotion) and function pre parsing (function promotion)
Variable promotion is to promote all variable declarations to the front of the current scope without promoting the assignment operation

 // Pre analysis case
   var num = 10;
   function fn(){
     console.log(num);
     var num = 20;
     console.log(num);
   }
   fn();
  //  Equivalent to the following code
   var num;
   function fn(){
    var num;
     console.log(num);//undefined
     num = 20;
     console.log(num);//20
   }
   num = 10;
   fn();
 function f1() {
      var a;
      a = b = c =9;//b. C direct assignment without var declaration when looking at global variables
      console.log(a);//9
      console.log(b);//9
      console.log(c);//9

    }
    f1();
    console.log(a);//report errors
    console.log(b);//9
    console.log(c);//9

Promote the declared function to the front and then promote the function in the function (the same operation)

5, object

In JavaScript, an object is an unordered collection of related attributes and methods. All transactions are objects, such as strings, values, arrays, functions, etc

1. Three ways to create objects

  • Creating objects with literals
  • Creating objects with new objects
  • Creating objects with constructors

(1) Creating objects with literals

Object literal: that is, {} curly brackets contain the properties and methods of the (object) expressing the specific transaction
be careful:
(1) For the attributes or methods inside, we take the form of key value pairs. Key attribute name: value attribute value
(2) Multiple attributes or methods are separated by commas
(3) The method colon is followed by an anonymous function

 var obj = {};//Create an empty object
   var obj = {
     name:'Zhang San',
     age :18,
     sex :'male',
     fn : function(){
       console.log('Hello');
     }
   }

Use object
Calling the object properties, we take the object name Attribute name

console.log(obj.name);

There is also a method object name ['property name'] for calling properties

console.log(obj['age']);

Method to call the object: object name. Please add () to the method name

obj.fn();

Summary of variables, attributes, functions and methods

(2) Creating objects with new objects

  • We use the equal sign = assignment method to add the properties and methods of the object
  • Each property and method ends with a semicolon
  • O in Object must be capitalized
//Creating objects with new objects
var obj = new Object();//Create an empty object
  obj.name = 'Nana';
  obj.sex = 'female';
  obj.age = 18;
  obj.skill = function(){
    console.log('sing');
  }
  console.log(obj.name);
} 

(3) Using constructors to create objects

Constructor: a special function that is mainly used to initialize an object, that is, to assign an initial value to an object member variable. It is always used with the new operator. We can extract some public attributes and methods from the object and encapsulate them into this function

Syntax format of constructor:

function Constructor name(){
	this.attribute = value;
	this.method = function(){}
}
new Constructor name();//Call constructor

be careful:
(1) Constructor names should be capitalized
(2) The constructor does not need return to return the result
(3) Call constructor must use new
(4) Property method must be preceded by this

//Creating object cases with constructors
 function Hero(uname, type, blood){
    this.name = uname;
    this.type = type;
    this.blood = blood;
    this.attack = function(at){
      console.log(at);
    }
  }
  var lianpo = new Hero('Lian Po','Power type','500 Blood volume');
  console.log(lianpo);
  var houyi = new Hero('offspring','Archer type','300 Blood volume');
  console.log(houyi);
  lianpo.attack('Melee');
  houyi.attack('Far war');

new keyword execution process:
(1) Create an empty object in memory
(2) Let this point to the new object
(3) Execute the code in the constructor. Add properties and methods to the new object
(4) Return this new object (so return is not required in the constructor)

2. Traversing objects

Using the for (variable In object) {}

 // Using traversal, you can output all the attributes in the object
    var obj = {
      name: 'beauty',
      age: 18,
      sex: 'female'
    }
    for (var k in obj) {
      console.log(obj[k]);
    }

6, Built in object

  • There are three kinds of objects in JavaScript: custom object, built-in object and browser object
  • Built in objects refer to the built-in objects of js language, which are used by developers and provide some common or most basic and necessary functions (properties and methods)
  • Advantages help us develop quickly
  • JavaScript provides several built-in objects: Math, Date, Array, String, etc
    Check documents
    ! [insert picture description here]( https://img-blog.csdnimg.cn/37f9794bbe3c4903b65c34b8e7d6813c.png

1.Math object

Case 1:

// Using objects to encapsulate their own mathematical objects, there are PI maximum and minimum values
var myMath = {
  PI: 3.14159,
  max:function(){
    var max = arguments[0];
    for (var i = 1; i < arguments.length-1; i++ ){
      if(arguments[i] > max){
        max = arguments[i];
      }
    }
    return max;
  },    //★ don't forget to add a comma
  min:function(){
    var min = arguments[0];
    for (var i = 1; i < arguments.length-1; i++ ){
      if(arguments[i] > min){
        min = arguments[i];
      }
    }
    return min;
  }

Case 2:

Case study:

// Math object random number method randomly generates numbers between 1 and 10, using math Random() built-in object
    function getRandomIntInclusive(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min; //Including maximum and minimum 
    }
    var re = getRandomIntInclusive(1, 10);
   while(true){//Dead cycle
    var num = prompt('Please enter a number');
    if(num > re){
      alert('The number is big');
    }else if(num < re){
      alert('The number is small');
    }else{
      alert('Bingo');
      break;
    }
  }

2.Date object

Is a constructor. You must use new
(1) Use Date to return the current parameter if there is no parameter

var date = new Date();
console.log(date);

3.Array object

(1) There are two ways to create an array:

     // 1. Use array literal
    var arr = [1,2,3];
    console.log(arr[0]);
    // 2. Use new Array()
    var arr1 = new Array();//An empty array was created
    var arr1 = new Array(2);//2 indicates that the length of the array is 2 and there are two empty array elements in it
    var arr1 = new Array(2,3);//Equivalent to [2,3], there are two array elements, 2 and 3
    console.log(arr1);

(2) Detect whether it is an array

//  Detect whether it is an array
  // (1)instanceof operator
  var arr = [];
  var obj = {};
  console.log(arr instanceof Array);
  console.log(obj instanceof Array);
  //  (2)Array. Isarray (parameter);
  console.log(Array,isArray(arr));
  console.log(Array,isArray(obj));

(3) Add or remove array element methods

 // 1.push add one or more array elements at the end of us
  var arr = [1,2,34];
  arr.push(4,'beauty');//Array elements are added directly
  console.log(arr.push(4,'beauty'));//Returns the length of the new array
  console.log(arr);
  // 2.unshift add at the beginning of the array
  arr.unshift(9,1);//Write array elements directly
  console.log(arr);

(4) Delete array elements

// pop deletes the last element of the array
    var arr = [1,2,3];
    console.log(arr.pop());//pop has no parameters. Only one element can be deleted at a time, and the deleted element is returned
    console.log(arr);
     // shift deletes the first element of the array
    console.log(arr.shift());//shift, like pop, deletes the first element of the array

Case:

// There is an array [1500120020021001800] containing wages. It is required to delete those whose wages exceed 2000 in the array and put the rest into the new array
    var arr = [1500, 1200, 2000, 2100, 1800];
    var newArray = [];
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] < 2000) {
        //newArray[newArray.length] = arr[i]; Previous writing
        newArray.push(arr[i]);//Now I have learned how to write after Push
      }
    }
    console.log(newArray);

(5) Array sorting

// Array sorting
    // 1. Flip array
    var arr = [1,2,3];
    arr.reverse();
    console.log(arr);
    // 2. Array sorting (bubble sorting)
    var arr1 = [1,2,3];
    arr1.sort(function(a,b){
      return a-b;
    });
    console.log(arr1);

(6) Array index method


Array de duplication case:

// Encapsulating a de duplication function unique requires the removal of duplicate elements in the array
    function unique(arr){
      var newArr = [];//Define an empty array
      for(var i = 0 ;i < arr.length; i++){
        if(newArr.indexOf(arr[i]) === -1){//indexOf means to find out whether there is an arr[i] element in newArr, which is equal to - 1 and No
          newArr.push(arr[i]);//Just put this element into the new array
        }
      }
      return newArr;
    }
    var demo = unique(['c','b','b','a','c','b']);

Convert array to string



(6) String object
JavaScript also provides three special reference data types: String, Number, and Boolean
The basic wrapper type is to wrap a simple data type into a complex data type, so that the data type has properties and methods

 // Basic package type
    var str = 'andy';
    console.log(str.length);
    //  Only objects have properties and methods, and complex data types have properties and methods
    // Why does a simple data type have a length attribute?
    // Basic packing type: packing simple data types into complex data types
    // (1) Wrapping simple data types into complex data types
    var temp = new String('andy');
    // (2) Give the value of the temporary variable to str
    str = temp;
    // (3) Destroy this temporary variable
    temp = null;

All methods of string will not modify the string itself (the string itself is immutable), and a new string will be returned after the operation is completed

// String object, return the position str.indexOf('character to find ', [starting position]) according to the character
    var str = 'I am pretty';
    console.log(str.indexOf('beautiful'));
    console.log(str.indexOf('beautiful',1));//Find from the first index number

// Find the location and number of occurrences of all o in the string "abcoefoxyozzopp"
    var str = "abcoefoxyozzopp";
    var f = str.indexOf('o');
    var num =0 ;
    while (f  !== -1){
      console.log(f);
      num++;
       f = str.indexOf('o',f + 1);
    }
    console.log("Number of occurrences"+num);

Returns characters based on position

 // Returns characters based on position
    // 1.charAt(index) returns characters according to position
    var str = 'andy';
    console.log(str.charAt(3));
    // Traverse all characters
    for (var i = 0; i < str.length; i++) {
      console.log(str.charAt(i));
    }
    // 2.charCodeAt(index) returns the character ASCII value of the corresponding index number. Purpose: to judge which key the user pressed
    console.log(str.charCodeAt(0));
    // 3.str[index]H5 NEW
    console.log(str[0]);
//  There is an object to judge whether there is the attribute object ['attribute name']
  var a = {
    age: 18
  }
  if(a['age']){
    console.log('There is this attribute in it');
  }else{
    console.log('There is no such attribute');
  }

Return string case:

// Judge the character that appears the most times in a string 'abcoefoxyozopp', and count its times
  var o = {};
  var str = 'abcoefoxyozzopp';
  for(var i = 0; i < str.length; i++){
    var chars = str.charAt(i);
    if(o[chars]){//o[chars] gets the attribute value
      o[chars]++;
    }else{
      o[chars] = 1;
    }
  }
  console.log(o);
  // Traversal object
  var max = 0;
  var ch = '';
  for(var k in o){
    // k gets the attribute name
    // o[k] gets the attribute name
    if(o[k] > max){
      max = o[k];
      ch = k;
    }
  }
  console.log(max);
  console.log('The maximum number of characters is'+ch);

Operation method of string:


Replace string:

7, Simple and complex types


Topics: Javascript Front-end Algorithm array