【Web Three-piece】JavaScript Arrays, Functions and Objects

1. Array

1.1 Basic Concepts

basic introduction:

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

  • Arrays can hold many values ​​under a single name, and these values ​​can also be accessed by reference to the index number.

The difference between JavaScript arrays and Java arrays:

  • Arrays in Java are used to represent a group in batchessame typeVariables
  • Arrays in JavaScript are used to represent a group in batchestypes are not necessarily the sameVariables
  • An array in JavaScript is not a pure number, but an array similar tokey-value pairan array of structs, essentially a JSobject(detailed in the New Elements section)

1.2 Create an array

Method 1 (recommended): use literals 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();

Notice:

  • JS arrays do not require elements of the same type

  • Arrays in JS canGet all elements of the array directly by outputting the array name, and also display the length of the array

    let arr = ["女足", "女排", "女篮"];
    console.log(arr);
    

    image-20220209140751334

1.3 Get array elements

Method: Access array elements by subscripting

let arr = ["女足", "女排", "女篮"];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);

image-20220209141316218

Notice:

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

    let arr = ["女足", "女排", "女篮"];
    console.log(arr[3]);
    console.log(arr[-1]);
    

    image-20220209141937543

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

    let arr = ["女足", "女排", "女篮"];
    arr = 1;
    console.log(arr);	// 此时 arr 就变成了一个数字类型的变量
    

    image-20220209142407027

1.4 Adding array elements

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

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

image-20220209152256484

Method 2: Add elements directly by subscripting

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

image-20220209152542039

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);

image-20220209153329207

Notice:

  • The index of an array in JS can not only be 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);
    

    image-20220209160728308

  • A JS array is actually a JS object. A JS object, like a Java class, can have properties and methods in it. andJS is a dynamically typed language, and its objects can dynamically add and delete properties during the running process.

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

  • JS objects can use the .sign to get or add properties, so when adding or acquiring properties as an object, you can also write like this

    let arr = [1, 2, 3];
    arr.a3 = 'aaa';	// 新增一个属性a3,同时设置值为 'aaa'
    arr.b3 = 'bbb';	// 新增一个属性b3,同时设置值为 'bbb'
    console.log(arr);
    console.log(arr.a3);
    console.log(arr['a3']);
    

    image-20220209162050574

  • 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 newly added array element is negative.. But you can't use the .sign , because the attribute name can't 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 deletions)

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

image-20220209163634887

Note: You cannot delete an element whose index is a string because the splice method's argument is required to be a number

image-20220209164110083

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 (retrieve the values ​​of the elements in the array in turn)

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

image-20220209164809063

2. Function

2.1 Basic Concepts

basic introduction:

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

Replenish:

  • Differences between functions, methods, and procedures

    the term difference
    function refers to a standalone function
    method Refers to a member function bound to a class
    process Refers to a function with 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 函数名(形参列表) {
    
    
    函数体
    return 返回值;
}

function call:

// 不考虑返回值
函数名(实参列表);

// 考虑返回值
返回值 = 函数名(实参列表);

Example code 1: Return value is not considered

// 函数声明/定义
function say(){
    
    
    console.log("hello!");
}

// 函数调用
say();

image-20220209191827499

Sample Code 2: Consider Return Values

// 函数声明/定义
function add(x, y){
    
    
    return x + y;
}

// 函数调用
let num = add(3, 7);
console.log(num);

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

image-20220209193757735

Notice:

  • There is no requirement for the order of function definitions and calls, that is, there is no function declaration restriction.
  • In JS, the same function can support parameters of different types, so in dynamically typed languages ​​such as JS, there is no need for syntax such as generics

2.3 About the number of parameters

In JS, the number of actual and formal parameters of a function can be mismatched

  • If the number of actual parameters is less than the formal parameters, the value of the additional formal parameters is undefined

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

    image-20220209194324331

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

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

    image-20220209194358050

2.4 Function Expressions

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

Sample code:

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

image-20220209202825547

2.5 Scope

basic introduction:

  • Scope indicates the effective scope of an identifier in the code
  • Before the ES6 standard, scopes were mainly divided into two
    • Global scope: takes effect in the entire script tag or in a separate js file
    • Function scope: takes effect inside a function

Sample code:

// 该 num 为全局变量
let num = 10;
console.log(num);

function test() {
    
    
    // 该 num 为局部变量
    let num = 20;
    console.log(num);
}
test();

image-20220209205712046

Notice:

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

2.6 Scope chain

Basic introduction: The inner function can access the variables of the outer function, and the chain search method is adopted (the search is performed in turn from the inside to the outside)

Sample code:

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

image-20220209210831851

When executing console.log(num), it will first look for num in the local scope of test2. If it is not found, it will continue to
search in test1. If it is not found, it will go to the global scope to find it.

3. Object

3.1 Basic Concepts

basic introduction:

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

3.2 Creating objects

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

// 创建了一个空的对象
let a = {
    
    };

// 创建了一个包含属性和方法的对象
let student = {
    
    
    name: '冰墩墩',
    height: 175,
    weight: 170,
    say: function() {
    
    
        console.log("北京冬奥会欢迎您");
    }
};
  • Properties and methods are organized in key-value pairs
  • Use the ,sign to and the comma after the last property or method is optional
  • Separate keys and values ​​with a :sign
  • The value of the method is an anonymous function

Method 2: Use to new Objectcreate an object

let student = new Object();
student.name: '冰墩墩',
student.height: 175,
student.weight: 170,
student.say: function() {
    
    
    console.log("北京冬奥会欢迎您");
}

Method 3: Use the constructor to create an object (the first two methods can only create one object at a time, and the constructor can create multiple objects)

// 构造函数
function 构造函数名(形参) {
    
    
	this.属性 =;
	this.方法 = function...
}
// 通过构造函数来进行赋值,已得到具体的对象
let obj = new 构造函数名(实参);
  • Use the this keyword inside a constructor to indicate that the object is currently being constructed
  • The first letter of the function name of the constructor is usually uppercase
  • Constructor does not need to return
  • When creating an object using the constructor, you must use the new keyword

3.3 Working with objects

You can use the properties and methods in the object through the .sign , and you can also add new properties. Here is an example of using objects in the form of constructors

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

let cat1 = new Cat('小黑', '中华田园猫');
console.log(cat1);

let cat2 = new Cat('刺球', '英国长毛猫');
console.log(cat2);

let cat3 = new Cat('咪咪', '波斯猫');
console.log(cat3);

image-20220209213730520

3.4 Execution process using constructor new

  1. First create an empty object in memory
  2. this points to the empty object just now
  3. Execute the code of the constructor, creating properties and methods for the object
  4. Return this object
    . Here is an example of using the object in the form of a constructor.

Guess you like

Origin blog.csdn.net/weixin_51367845/article/details/122850512