[Part IV | JavaScript Basics] 3: Functions, Scope and Preparsing, Objects

Table of contents

| function

Declaration and call

parameter

return value

arguments (JS-specific knowledge points)

Named and Anonymous Functions

| scope

Global and local, JS5 does not have block-level scope

The Principle of Proximity: The Scope Chain

| Pre-parsing (important)

Introduction: Four sentence-position-induced phenomena

The principle of the above phenomenon: JS compilation process [important!

Pre-analysis related interview assessment points

| custom object

create object

Use object properties and methods

【Analysis】Variables, properties, functions, methods

The four steps performed by the new keyword

Object traversal uses for...in...

Summarize

| built-in object

Official API

Math object Math

Date object Date

Array object Array

Basic Wrapper Type & String Immutable

String object String

[Case] ​​Count the characters with the most occurrences


| function

Declaration and call

 

parameter

  • The formal parameter declaration of JS does not need to declare the type! Just write the variable name directly

The number of function parameters and actual parameters does not match

 

 

After testing, modifying the elements of the array in the function parameter is equivalent to modifying the element of the corresponding address of the array

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var nums = [1,2,3];
        alert(nums);// 1 2 3

        changeArrayElements(nums);
        function changeArrayElements(array) {
            array[1] = 5;
        }

        alert(nums);// 1 5 3


    </script>
</head>
<body>
    
</body>
</html>

 

 

return value

Note the difference between JS return value and Java

  • There is no need to write the return type in the statement of the function declaration

  • Just write return XXX;

  • All functions in JS have a return value! If you do not write return, there will be a default return value: undefined

  • Code after the return statement is not executed. return can only return one value. If multiple values ​​are separated by commas, the last one shall prevail.

code example

		function getStr(){
            return 'AAA';
        }

        function getUndefined(){

        }

        alert(getStr()); //AAA
        alert(getUndefined()); //undefined

 

 

arguments (JS-specific knowledge points)

  • The role of arguments: store all the actual parameters passed.

  • Essence is an object. A bit similar to Java's map

  • All JS functions have built-in this object, feel free to use it!

introduce

example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>

        useArguments(1,2,3,4);

        // 若形参的个数不确定,则我们干脆不写形参了。这样的话,我们的JS会自动帮我们把传进来的形参,放进arguments[]数组中
        function useArguments() {
            // arguments的本质是一个对象。有点类似于Java的map
            console.log(arguments); //Arguments { 0: 1, 1: 2, 2: 3, 3: 4, … }
        }
    </script>
</head>
<body>
    
</body>
</html>

 


Named and Anonymous Functions

introduce

Named function:

anonymous function:

 


Precautions

  • For named functions, the code to call the function can be placed before or after the declared function;

    For anonymous functions, the code of the function call must be written after the function body

  • Anonymous function declaration var XXX = function(){...}; At this time, XXX stores a function


| scope

Global and local, JS5 does not have block-level scope

  • The scope of JS is similar to that of Java. Both are global scopes and local scopes within functions.

  • But JS has a special case: variables declared inside functions are also global variables. as follows

  • Special attention should be paid to: Except for functions, JS5 is not block-level scoped! That is: the variables defined in if and for are global variables! After JS6, variables in if and for are local variables.

 

 

The Principle of Proximity: The Scope Chain

In human terms, there are two variables with the same name. When calling a variable with this name in a function, which variable is used? The principle of proximity

 example


| Pre-parsing (important)

Introduction: Four sentence-position-induced phenomena

JS is an interpreted language, that is: run line by line, compile line by line. So this is somewhat strict about the order of the code. Some examples are given below

 


The principle of the above phenomenon: JS compilation process [important!

Knowledge points [important!

Explanation of the Four Sentence Position Phenomena

The reason for undefined in the second case: JS precompilation, the variable declaration var nume is promoted to the front of the current scope, but the assignment operation is not promoted, so it is equivalent to no assignment, and the output is undefined

 

The third case: the reason why the call of the named function can take effect before and after the declaration statement: JS will promote the function declaration to the front of the current scope, and then the calling statement is behind the precompiled function declaration statement , so you can call ~

 

The principle of error reporting in the fourth case: a fun variable is declared first, but the function body is not assigned. At this time, fun() is called, but JS thinks that JS is a variable instead of a function at this time, so it outputs "This is not a function" error

 

 

 


Pre-analysis related interview assessment points

 

The above code is pre-parsed as:

Variable hoisting: the declaration is brought to the front, but no value is assigned; function hoisting: the function declaration is brought to the front, but it is not called

var num;

function fun() {

var num;

console.log(num);

num = 20;

}

num = 10;

fun();

The final output is: undefined

var a=b=c=9; is equivalent to var a=9 ; b=9 ; c=9; a is a local variable, b and c are global variables

The above code is pre-parsed as:

// function promotion

function f1() {

//variable promotion

var a;

a=b=c=9;

console.log(a);

console.log(b);

console.log(c);

}

f1(); //9 9 9

console.log(c);// 9

console.log(b);// 9

console.log(a);// local variable, error

 

| custom object

create object

Create objects using literals

  • { } is expressed in the form of key-value pairs. var only needs to be declared outside the object. Properties within an object are linked using key-value pairs [colon]. An anonymous function inside an object

  • Note that after the object name and between the curly braces is = between the attribute name and the attribute value is: after the attribute value is not; 

Create objects with new Object

Object is a fixed form. Note that O is uppercase

 

  • Use the equal sign to append the assignment, followed by a semicolon at the end

  • Objects in JS can add attributes to them

        //new关键字定义对象
        var obj2 = new Object();
        obj2.name = 'Klee2';
        obj2.age = 10;
        obj2.f2 = function() {
            alert('Hi~ ');
        }
        obj2['name'];
        obj2.f2();

 

Create objects using constructors (commonly used)

  • Constructor does not need to write return

        //构造函数定义对象
        function Person(name , age , sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;

            this.f3 = function() {
                alert('name = '+name+';age = '+age+';sex = '+sex);
            }
        }
        obj3 = new Person('Klee3 , 12 , Women');
        console.log(obj3.name);
        obj3.f3();

 


Use object properties and methods

The first method calls method one

对象名.属性名;

The second method calls the property

对象名['属性名'];

functions using objects

  • Note: To call an anonymous function (method), you need to add a () after the property name

  • The function defined outside the object is called [function], and the function defined inside the object is called [method]

对象名.函数名();

code example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        //字面量定义对象
        var obj1 = {
            name : 'Klee',
            age : 9,
            f1 : function() {
                alert('I\'m Klee');
            }
        }
        //调用对象
        console.log(obj1.name);   //klee
        console.log(obj1['name']);  //klee
        obj1.f1();


    </script>
</head>
<body>
    
</body>
</html>

【Analysis】Variables, properties, functions, methods

Variables: use the var keyword to declare and assign values ​​individually. Such as var num = 10;

Attribute: In a class, there is no need to declare the keyword var, and a key-value pair is used for assignment. Such as var obj = { num : 10; }

Function: declare and call separately. Use the function name ( ) alone when calling;

Method: Declared in the object, which is equivalent to an anonymous function. When calling, pass the object name. method name ();


The four steps performed by the new keyword


Object traversal uses for...in...


 


Summarize

 

 

| built-in object

Official API

It is better to teach a man how to fish than to teach him how to fish. In the future, you can come here to find some built-in objects of JS

MDN: MDN Web Docs


Math object Math

Math can directly call the methods inside. Math does not need a constructor to create objects

basic operations

random function

 

 sample code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var nums = [-1,0,2,3,3];

        //基本运算
        console.log(Math.PI); //3.1415...
        console.log(Math.floor(2.33)); //向下取整 2
        console.log(Math.ceil(2.33)); //向上取整 3
        console.log(Math.round(-2.5)); //变大的四舍五入  -2
        console.log(Math.round(2.5)); //变大的四舍五入 3
        console.log(Math.abs(-2.3)); //绝对值 2.3
        console.log(Math.max(3,4,5)); //最大值 3
        console.log(Math.min(-1,1,0)); //最小值 -1
        console.log(Math.max()); //没有参数 则Math.max返回  -Infinity
        console.log(Math.max(1,'Klee'));; //有非数字,则返回 NaN
        console.log(Math.min());  //没有参数 则Math.min返回  Infinity

        
        // 函数:获取[min,max]的整数。  Math.Random()获取 [0,1)的小数
        function getRandom(min , max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        console.log(getRandom(20,40));
        
    </script>
</head>
<body>
    
</body>
</html>

 

 

Date object Date

The date object Date needs to be created through a constructor, and it needs to be instantiated before it can be used

create date object

date object formatting

  • Default format: Ugly, we need to learn to format time.

  • Need to get the specified part of the date, so we have to manually get this format

 

Get date total milliseconds

  • Date objects are based on the number of milliseconds since January 1, 1970 (UTC)

  • We often use the total number of milliseconds to calculate time because it is more precise

 

Code examples of the above three knowledge points

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>


        //构造日期对象
        var date1 = new Date();//构造函数没有参数,则返回当前时间
        console.log(date1);

		//构造函数有参数,数字格式的时间   XXXX,XX,XX  则产生对应时间的date(JS的月份从0开始,数字为n,则JS认为是n+1月)
        var date2 = new Date(2001,1,1);
        console.log(date2);  //返回的是Febrary 2月【即通过数字型格式参数赋值的月份,比规定的要大一个月】

        var date3 = new Date('2001-1-1 8:8:8');//使用字符串时间的格式  'XXXX-XX-XX XX:XX:XX' (推荐!!!!)
        console.log(date3);  //通过字符串格式产生的date对象,月份和参数一致



        //日期格式化
        var year = date1.getFullYear();
        var month = date1.getMonth();
        var day = date1.getDate();
        console.log('今天是'+year+'年'+month+'月'+day+'日'); //今天是2022年4月23日【错误!需要注意,获取到的month从0开始,因此需要加1】
        console.log('今天是'+year+'年'+(month+1)+'月'+day+'日'); //今天是2022年5月23日 正确


        
        //当前日期的毫秒值(距1970.1.1)
        var date4 = new Date();
        console.log(date4.valueOf()); //1653310553063
        console.log(date4.getTime()); //1653310553063

        var dateTime = +new Date(); //+new Date() 返回的就是总的毫秒数
        console.log(dateTime); //1653310553063

        var dateTime2 = Date.now();//Html5新方法 有兼容问题
        console.log(dateTime2); //1653310553063

    </script>
</head>
<body>
    
</body>
</html>

 


Array object Array

Determine whether it is an array

  • The instanceof operator can determine whether an object belongs to a certain type

  • Array.isArray() is used to determine whether an object is an array, isArray() is a method provided in HTML5

var arr = [1, 23];
var obj = {};
console.log(arr instanceof Array); // true
console.log(obj instanceof Array); // false
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false

Add and delete elements to the array

array sort

 

Array index method

 

array to string

 

other operations

 

All code samples for the above operations

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var nums = [1,2,3,4,5,6];

        //判断是否为数组
        console.log(nums instanceof Array);//true
        console.log(Array.isArray(nums));//true
        console.log(nums.toString());//1 2 3 4 5 6


        //push向末尾增加一个 / 多个元素(改变原数组)
        nums.push(7,8);
        console.log(nums.toString()); //1 2 3 4 5 6 7 8 

        
        //pop删除最后一个元素(改变原数组)
        nums.pop();
        console.log(nums.toString());//1 2 3 4 5 6 7


        //unshift向开头增加一个 / 多个元素(改变原数组)
        nums.unshift(-2,-1,0);
        console.log(nums.toString());//-2 -1 0 1 2 3 4 5 6 7    


        //shift删除第一个元素(改变原数组)
        nums.shift();
        console.log(nums.toString());//-1 0 1 2 3 4 5 6 7


        //数组reverse()颠倒数组(改变原数组)
        var nums2 = nums.reverse();
        console.log(nums2.toString());//7,6,5,4,3,2,1,0,-1
        console.log(nums.toString());//7,6,5,4,3,2,1,0,-1


        //数组sort( )排序数组
        var nums3 = [3,5,2,4,5,6,5,3,2,4,4,2];
        nums3.sort();
        console.log(nums3.toString());//2,2,2,3,3,4,4,4,5,5,5,6


        //使用indexOf()查找元素的第一个索引
        console.log(nums3.indexOf(3));//3  即:元素3第一次出现的索引是3
        //使用lastIndexOf()查找元素的最后一个索引
        console.log(nums3.lastIndexOf(5));//10


        //除了toString,join('分隔符') 也可以把数组转为字符串
        console.log(nums3.join(' | '));//2 | 2 | 2 | 3 | 3 | 4 | 4 | 4 | 5 | 5 | 5 | 6


        //concat()用来连接两个数组为一个新数组
        var nums4 = [1,2];
        var nums5 = [3,4];
        var nums6 = nums4.concat(nums5);
        console.log(nums6.toString());//1,2,3,4


        //slice(beginIndex , endIndex)返回被截取项目的新数组,返回的是 [begin , end) 上的元素
        var nums7 = nums6.slice(1,3);
        console.log(nums7.toString());//2,3


        //splice(开始的索引数 , 要删除的个数)
        var nums8 = [1,2,3,4,5,6];
        nums8.splice(2,3);//从索引2开始,删除3个数
        console.log(nums8.toString());//1,2,6

    </script>
</head>
<body>
    
</body>
</html>

 


Basic Wrapper Type & String Immutable

basic packaging type

Strings are immutable

 


String object String

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

return position by character

application

Return characters by position (emphasis added)

 

ASCII table

String manipulation methods

 

character to replace index

 

put array → string

array.join('');

 Detailed code example for the above syntax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        var str1 = 'Klee';

        //根据字符返回位置
        console.log(str1.indexOf('K'));//0
        console.log(str1.indexOf('K',1));//('K',1)代表从索引=1的地方开始查找。因为没有找到K 所以返回的是 -1
        console.log(str1.lastIndexOf('e'));//3


        //根据位置返回字符
        var c1 = str1.charAt(0);
        console.log(c1);//K
        var c2 = str1[0];
        console.log(c2);//K H5、IE8+、CharAt支持

        
        //根据位置返回字符的ASCII码
        console.log(str1.charCodeAt(0));//75  (K的ASCII码是75)

        //substr(开始索引,字符个数) 截取字符串
        console.log(str1.substr(1,2));//le

        //replace(被替换字符串 ,要替换的字符串)
        console.log(str1.replace('le','el'));//leke


    </script>
</head>
<body>
    
</body>
</html>

 


[Case] ​​Count the characters with the most occurrences

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        // 有一个对象 来判断是否有该属性 对象['属性名']
        var o = {
            age: 18
        }
        if (o['sex']) {
            console.log('里面有该属性');

        } else {
            console.log('没有该属性');

        }

        //  判断一个字符串 'abcoefoxyozzopp' 中出现次数最多的字符,并统计其次数。
        // o.a = 1
        // o.b = 1
        // o.c = 1
        // o.o = 4
        // 核心算法:利用 charAt() 遍历这个字符串
        // 把每个字符都存储给对象, 如果对象没有该属性,就为1,如果存在了就 +1
        // 遍历对象,得到最大值和该字符
        var str = 'abcoefoxyozzopp';
        var o = {};
        for (var i = 0; i < str.length; i++) {
            var chars = str.charAt(i); // chars 是 字符串的每一个字符
            if (o[chars]) { // o[chars] 得到的是属性值
                o[chars]++;
            } else {
                o[chars] = 1;
            }
        }
        console.log(o);
        // 2. 遍历对象
        var max = 0;
        var ch = '';
        for (var k in o) {
            // k 得到是 属性名
            // o[k] 得到的是属性值
            if (o[k] > max) {
                max = o[k];
                ch = k;
            }
        }
        console.log(max);
        console.log('最多的字符是' + ch);
    </script>
</head>

<body>

</body>

</html>

Guess you like

Origin blog.csdn.net/m0_57265007/article/details/127962037