[Web three piece set] arrays, functions and objects of JavaScript

Article catalogue

1. Array

1.1 basic concepts

Basic introduction:

  • An array is a special variable that can hold more than one value at a time.

  • Arrays can hold many values under a single name, and they can also be accessed by referencing the index number.

Differences between JavaScript arrays and Java arrays:

  • Arrays in Java are used to represent a group of variables of the same type in batches
  • Arrays in JavaScript are used to represent a group of variables with different types in batches
  • The array in JavaScript is not a pure number, but an array similar to the key value pair structure. In essence, it is a JS object (described in detail in the new elements section)

1.2 creating arrays

Method 1 (recommended): use literal quantity to create

let arr1 = [];
let arr2 = [1, 2, 3];
let arr3 = [1, "hello", false, null];

Method 2: use the new keyword to create

let arr4 = new Array();

be careful:

  • JS arrays do not require the same type of elements

  • JS array can directly get all elements of the array by outputting the array name, and the length of the array will also be displayed

    let arr = ["women's soccer team", "women 's volleyball", "women 's basketball"];
    console.log(arr);
    

1.3 get array elements

Method: access array elements by subscript

let arr = ["women's soccer team", "women 's volleyball", "women 's basketball"];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);

be careful:

  • If the subscript exceeds the range of the array, the element is read and the result is undefined

    let arr = ["women's soccer team", "women 's volleyball", "women 's basketball"];
    console.log(arr[3]);
    console.log(arr[-1]);
    

  • If you assign a direct value to an array name, the array becomes a single variable and the elements in the previous array are gone

    let arr = ["women's soccer team", "women 's volleyball", "women 's basketball"];
    arr = 1;
    console.log(arr);	// At this point, arr becomes a numeric variable
    

1.4 adding array elements

Method 1: add by modifying length (when the value of length is increased, the initial value of the added array element is undefined)

let arr = [1, 2, 3];
arr.length = 5;
console.log(arr);
console.log(arr[3], arr[4]);

Method 2: add elements directly through subscript

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

Method 3: append elements through push (the appended elements are at the end of the array)

let arr = [1, 2, 3];
arr.push(4);
arr.push(5);
console.log(arr);

be careful:

  • The index of an array in JS can be not only a number, but also a string, which is more like a key value pair structure

    let arr = [1, 2, 3];
    arr['a3'] = 'aaa';
    arr['b3'] = 'bbb';
    console.log(arr);
    

  • JS array is essentially a JS object. Like Java classes, JS objects can have properties and methods. And JS is a dynamic type language. Its objects can dynamically add and delete attributes during operation

  • In the code of the above example, the first three elements are simply stored in the way of array, which is the real value of JS array. The elements added in the way used later are actually the attributes added by the array as the identity of the object. Therefore, the length of the array is based on the number of arrays stored

  • JS objects can be used Number to get or add attributes, so you can also write this when talking about adding or obtaining attributes as an object

    let arr = [1, 2, 3];
    arr.a3 = 'aaa';	// Add a new attribute a3 and set the value to 'aaa'
    arr.b3 = 'bbb';	// Add a new attribute b3 and set the value to 'bbb'
    console.log(arr);
    console.log(arr.a3);
    console.log(arr['a3']);
    

  • When the index of the array is negative, it is equivalent to treating the array as an object, that is, the length of the array will not increase because the index of the new array element is negative. But it cannot be used like a string To get or add an object, because the property name cannot start with a number

1.5 deleting array elements

Method: delete elements through the splice method (the first parameter of this method is the starting position of deletion, and the second parameter is the number of deleted elements)

let arr = [1, 2, 3];
arr.splice(1,1);
console.log(arr);

Note: you cannot delete the element that indexes the array as a string, because the parameter of the splice method requires a number

1.6 traversing array elements

Method 1: directly use the for loop to traverse the array

let arr = [1, 2, 3];
for(let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

Method 2: use for in to traverse the array (take out the subscripts of the elements in the array in turn)

let arr = [1, 2, 3];
for(let i in arr) {
    console.log(arr[i]);
}

Method 3: use for of to traverse the array (take out the values of the elements in the array in turn)

let arr = [1, 2, 3];
for(let value of arr) {
    console.log(value);
}

2. Function

2.1 basic concepts

Basic introduction:

A function is a reusable block of code that is event driven or executed when it is called. In addition to functions, there are other names in different languages, such as method and produce.

Supplement:

  • Differences in functions, methods and procedures

    term

    difference

    function

    Refers to an independent function

    method

    It refers to a member function bound to a class

    process

    It refers to a function that has no return value (void)

  • Functions can be defined inside functions

  • The inner function can access the local variables of the outer function

2.2 syntax format

Function declaration / function definition:

function Function name(parameter list ) {
    Function body
    return Return value;
}

Function call:

// Return values are not considered
 Function name(Argument list);

// Consider return value
 Return value = Function name(Argument list);

Example code 1: return values are not considered

// Function declaration / definition
function say(){
    console.log("hello!");
}

// function call
say();

Example code 2: consider the return value

// Function declaration / definition
function add(x, y){
    return x + y;
}

// function call
let num = add(3, 7);
console.log(num);

let str = add('hello', 'world');
console.log(str);

be careful:

  • There are no requirements for the definition of functions and the order of calls, that is, there is no restriction on function declaration
  • In JS, the same function can support different types of parameters, so in dynamic type languages such as JS, there is no need for syntax such as generics

2.3 number of parameters

In JS, the number of arguments and formal parameters of a function can not match

  • If the number of arguments is less than the formal parameter, the additional formal parameter value is undefined

    function test(x ,y) {
        console.log(x);
        console.log(y);
    }
    test(1);
    

  • If there are more arguments than formal parameters, the extra arguments will not participate in the operation of the function

    function add(x ,y) {
        return x + y;
    }
    console.log(add(1, 2, 3));
    

2.4 function expression

Basic introduction: in JS, a function can be used as an expression. Write a function as an anonymous function, assign it to a variable, and then use this variable to call the function

Example code:

let add = function(x, y){
    return x + y;
}
console.log(add(3, 8));

2.5 scope

Basic introduction:

  • The scope represents the valid range of an identifier in the code
  • Before the ES6 standard, the scope was mainly divided into two parts
    • Global scope: takes effect in the whole script tag or in a separate js file
    • Function scope: takes effect inside a function

Example code:

// This num is a global variable
let num = 10;
console.log(num);

function test() {
    // This num is a local variable
    let num = 20;
    console.log(num);
}
test();

be careful:

  • The scope of the variable created by let is a block level scope, which only takes effect in the current code
  • The scope of variables created by var is a function level scope, which is valid in the whole function
  • When creating a variable, if neither let nor var is written, the created variable is a global variable

2.6 scope chain

Basic introduction: internal functions can access the variables of external functions, which adopts the chain search method (search from inside to outside in turn)

Example code:

let num = 1;
function test1() {
	function test2() {
		console.log(num);
	}
	test2();
}
test1();

Execute console Log (Num), first find num in the local scope of test2. If it is not found, continue to test1
Find, If not, go to the global scope

3. Object

3.1 basic concepts

Basic introduction:

  • Object refers to a specific thing. In JS, strings, values, arrays and functions are objects
  • Each object contains several properties and methods
    • Attributes: characteristics of things
    • Method: the behavior of things
  • The objects in JS do not depend on classes, and the type of objects is Object
  • The objects in JS do not need to be decorated with permission modifiers, and all properties can be considered public

3.2 creating objects

Method 1 (recommended): use {} to create objects

// An empty object was created
let a = {};

// An object containing properties and methods is created
let student = {
    name: 'Bing Dwen Dwen',
    height: 175,
    weight: 170,
    say: function() {
        console.log("Welcome to the Beijing Winter Olympics");
    }
};
  • Properties and methods are organized in the form of key value pairs
  • Key value pairs are separated by numbers, and the comma after the last property or method is optional
  • Key and value are separated by:
  • The value of the method is an anonymous function

Method 2: create an object using new Object

let student = new Object();
student.name: 'Bing Dwen Dwen',
student.height: 175,
student.weight: 170,
student.say: function() {
    console.log("Welcome to the Beijing Winter Olympics");
}

Method 3: use the constructor to create objects (the first two methods can only create one object at a time, while using the constructor can create multiple objects)

// Constructor
function Constructor name(Formal parameter) {
	this.attribute = value;
	this.method = function...
}
// The specific object has been obtained through the assignment through the constructor
let obj = new Constructor name(Argument);
  • Use the this keyword inside the constructor to indicate that the object is currently being constructed
  • The function name of the constructor is generally capitalized
  • Constructor does not require return
  • When creating an object using a constructor, you must use the new keyword

3.3 object of use

Pass Number to use the properties and methods in the object, or add properties. Here is an example of using objects in the way of constructors

function Cat(name, type) {
    this.name = name;
    this.type = type;
    this.miao = function() {
        console.log('Meow');
    }
}

let cat1 = new Cat('Little black', 'Chinese garden cat');
console.log(cat1);

let cat2 = new Cat('Thorn ball', 'British Longhair ');
console.log(cat2);

let cat3 = new Cat('Mimi', 'Persian cat');
console.log(cat3);

3.4 execution process using constructor new

  1. First create an empty object in memory
  2. this points to the empty object just
  3. Execute the code of the constructor to create properties and methods for the object
  4. Return this object
    Here is an example of using objects in the way of constructors

Keywords: Javascript Front-end html

Added by st89 on Wed, 09 Mar 2022 06:57:36 +0200