[JaveWeb Tutorial] (2) Web front-end basics: Getting started with JavaScript is no longer difficult: an article teaches you to easily master the basic syntax and functions of JavaScript

Insert image description here

HTML has completed the shelf, and CSS has been beautified, but the web page is dead. We need to inject soul into it, so next we need to learn JavaScript. This language will allow our pages to interact with users.

1 Introduction

Provide information through code/js effect demonstration for effect demonstration. Open it through the browser, we click the theme 5 button, and the theme of the page changes, so js can make our page more intelligent and allow the page to interact with users.

Insert image description here

2 Introduction method

Similarly, js code is also written in html, so how to introduce js code into html? Mainly through the following two introduction methods:

**First way:** Internal script, define JS code in HTML page

  • JavaScript code must be placed between <script></script> tags
  • In an HTML document, you can place any number of <script>s anywhere
  • Generally, the script is placed at the bottom of the <body> element to improve display speed.

example:

<script>
    alert("Hello JavaScript")
</script>

**Second method:** The external script defines the JS code in the external JS file and then introduces it into the HTML page

  • The external JS file only contains JS code and does not contain the <script> tag.
  • The <script> tag that introduces external js must be a double tag

example:

<script src="js/demo.js"></script>

Note: There is only js code in demo.js, no <script> tag

Next, we use VS Code to write code and demonstrate two ways to introduce js in html.

Step 1: Create a file named 10.JS-Introduction method.html in VS Code

Step 2: Introduce js according to the first internal script method mentioned above, and write the following 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>JS-引入方式</title>
    <!-- 内部脚本 -->
    <script>
        alert('Hello JS');
    </script>
</head>
<body>
</body>
</html>

Step 3: The effect of opening the browser is as shown in the figure:

Insert image description here

Step 4: Next, demonstrate the external script, comment out the internal script, then create a js directory at the same level as the css directory, and then create a file named demo.js:

Insert image description here

Step 5: Write the following js content in demo.js:

alert('Hello JS2');

Step 6: Comment out the previous internal script code and add the <script> tag to introduce the external demo.js file. The specific code is as follows:

<!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>JS-引入方式</title>
    <!-- 内部脚本 -->
    <!-- <script>
        alert('Hello JS');
    </script> -->

    <!-- 外部脚本 -->
    <script src="js/demo.js"></script>
</head>
<body>

</body>
</html>

Step 7: The browser refresh effect is as shown in the figure:

Insert image description here

3 Basic grammar

3.1 Writing grammar

After mastering the introduction method of js, then we need to learn how to write js. The first thing we need to master is the writing grammar of js. The grammar rules are as follows:

  • Case Sensitivity: Like Java, variable names, function names, and everything else are case sensitive

  • The semicolon at the end of each line is optional

  • Braces represent blocks of code

  • Note:

    • Single line comment: // comment content

    • Multi-line comments: /* Comment content*/

We need to use the 3-minute output statement in js to demonstrate the writing syntax.

api describe
window.alert() warning box
document.write() Output content in HTML
console.log() Write to browser console

Next, we choose to use VS Code to expose three types of input statements to demonstrate the writing syntax of js.

Step 1: Create a file named 11.JS-Basic Syntax-Output Statement.html in VS Code

Step 2: According to the basic grammar rules, write the code for the three output statements and add comments. The specific code is as follows;

<!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>JS-基本语法</title>
</head>
<body>
    
</body>
<script>
    /* alert("JS"); */
    //方式一: 弹出警告框
    window.alert("hello js");
</script>
</html>

The browser opens as shown in the figure:

Insert image description here

We comment out the above code and add the code document.write("hello js"); to output the content:

<!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>JS-基本语法</title>
</head>
<body>
    
</body>
<script>
    /* alert("JS"); */

    //方式一: 弹出警告框
    // window.alert("hello js");

    //方式二: 写入html页面中
    document.write("hello js");

</script>
</html>

Refresh the browser, the effect is as shown in the figure:

Insert image description here

Finally, we use console.log(“hello js”); to write to the console and comment out the previous 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>JS-基本语法</title>
</head>
<body>
    
</body>
<script>
    /* alert("JS"); */

    //方式一: 弹出警告框
    // window.alert("hello js");

    // //方式二: 写入html页面中
    // document.write("hello js");

    //方式三: 控制台输出
    console.log("hello js");
</script>
</html>

Capture packets with browser F12 and go to the console page, as shown in the figure:

Insert image description here

3.2 Variables

Now that you know the writing syntax, variables are indispensable to a programming language, so next we need to learn the declaration of variables in js. In js, the declaration of variables is still different from that in java. First of all, variables are mainly declared in js through the following three keywords:

Keywords explain
was Keywords used for variable declaration in early ECMAScript5
let A new keyword for variable declaration in ECMAScript6. Compared with var, let only takes effect within a code block.
const If a constant is declared, once the constant is declared, it cannot be modified.

When declaring variables in js, you need to pay attention to the following points:

  • JavaScript is a weakly typed language, and variables can store values ​​of different types.
  • Variable names need to follow the following rules:
    • The constituent characters can be any letters, numbers, underscore (_), or dollar sign ($)
    • Numbers cannot begin with
    • It is recommended to use camel case naming

Next we need to write code through VS Code to demonstrate the definition of variables in js

Step 1: Create a file named 12.JS-Basic Syntax-Variables.html in VS Code:

Step 2: Write the 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>JS-基础语法</title>
</head>
<body>
    
</body>
<script>

    //var定义变量
    var a = 10;
    a = "张三";
    alert(a);

</script>
</html>

You can see that the browser pops up Zhang San

Insert image description here

In js, variables declared by var can accept values ​​of any data type. And the role of variables declared by var is global. Comment out the previous code and add the following code:

<script>
    //var定义变量
    // var a = 10;
    // a = "张三";
    // alert(a);

    //特点1 : 作用域比较大, 全局变量
    {
      
      
        var x = 1;
    }
    alert(x);
</script>

The browser still pops up successfully:

Insert image description here

Moreover, variables declared with the var keyword can be defined repeatedly. Modify the code as follows:

{
    
    
     var x = 1;
     var x = "A";
}
alert(x);
    

The browser pop-up content is A

Insert image description here

Therefore, ECMAScript 6 added the let keyword to define variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let keyword is located, and repeated declarations are not allowed. Comment out the previous code and add the following code:

<script>

    //var定义变量
    // var a = 10;
    // a = "张三";
    // alert(a);

    //特点1 : 作用域比较大, 全局变量
    //特点2 : 可以重复定义的
    // {
      
      
    //     var x = 1;
    //     var x = "A";
    // }
    // alert(x);
    
    //let : 局部变量 ; 不能重复定义 
    {
      
      
        let x = 1;
    }
    alert(x);

</script>

The browser is opened, f12 captures the packet, and when I come to the console page, I find an error and the variable is not defined, indicating that the variable declared by let does not take effect outside the code block.

Insert image description here

Then we use let to repeatedly define variables. The code modification is as follows: we found that idea directly reported an error for us, indicating that variables declared by let cannot be repeatedly defined.

Insert image description here

In ECMAScript6, the const keyword is also added to declare constants, but once declared, the value of the constant cannot be changed. Comment out the previous content and add the following code:

    const pi = 3.14;
    pi = 3.15;
    alert(pi);

I captured the packet with browser F12, and when I came to the console page, I found that an error was reported directly.

Insert image description here

We end the explanation of variables here. The complete code is as follows:

<!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>JS-基础语法</title>
</head>
<body>
    
</body>
<script>

    //var定义变量
    // var a = 10;
    // a = "张三";
    // alert(a);

    //特点1 : 作用域比较大, 全局变量
    //特点2 : 可以重复定义的
    // {
      
      
    //     var x = 1;
    //     var x = "A";
    // }
    // alert(x);

    //let : 局部变量 ; 不能重复定义 
    // {
      
      
    //     let x = 1;
    //     alert(x);
    // }
    
    //const: 常量 , 不能给改变的.
    const pi = 3.14;
    pi = 3.15;
    alert(pi);

</script>
</html>

3.3 Data types and operators

Although js is a language with weak data types, data types also exist in js. The data types in js are divided into: primitive types and reference types. The specific types are as follows

type of data describe
number Numbers (integers, decimals, NaN (Not a Number))
string String, both single and double quotes are acceptable
boolean Boolean. true, false
null Object is empty
undefined When a declared variable is not initialized, the default value of the variable is undefined

Use the typeof function to return the data type of the variable. Next we need to write code to demonstrate the data type in js

Step 1: Create a file named 13. JS-Basic Syntax-Data Type.html in VS Code

Step 2: Write the following code, and then directly observe the data types one by one:

<!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>JS-数据类型</title>
</head>
<body>

</body>
<script>

    //原始数据类型
    alert(typeof 3); //number
    alert(typeof 3.14); //number

    alert(typeof "A"); //string
    alert(typeof 'Hello');//string

    alert(typeof true); //boolean
    alert(typeof false);//boolean

    alert(typeof null); //object 

    var a ;
    alert(typeof a); //undefined
    
</script>
</html>

Now that we are familiar with the data types of js, we need to learn the algorithms in js. Most of the operation rules in js are consistent with those in java. The specific operators are as follows:

Arithmetic rules operator
arithmetic operators + , - , * , / , % , ++ , –
assignment operator = , += , -= , *= , /= , %=
comparison operator > , < , >= , <= , != , == , === Note that == will perform type conversion, === will not perform type conversion
Logical Operators && , || , !
ternary operator Conditional expression? true_value: false_value

Next, we will demonstrate the algorithm in js through code, mainly remembering the inconsistencies between js and java.

Step 1: Create a file named 14. JS-Basic Syntax-Operator.html in VS Code

Step 2: Write the code

In js, most of the operation rules are consistent with those in java, but there are differences between == and === in js.

  • ==: Only compares whether the values ​​are equal and does not distinguish between data types. Even if the types are inconsistent, == will automatically convert the type for worthy comparison.
  • ===: Not only compares values, but also compares types. If the types are inconsistent, return false directly.
<!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>JS-运算符</title>
</head>
<body>
    
</body>
<script>
     var age = 20;
     var _age = "20";
     var $age = 20;
    
     alert(age == _age);//true ,只比较值
     alert(age === _age);//false ,类型不一样
     alert(age === $age);//true ,类型一样,值一样

</script>
</html>

In js, although data types are not distinguished, sometimes when numerical calculations are involved, type conversion is still required. In js, you can use the parseInt() function to convert other types into numerical types. Comment the previous code and add the following code:

// 类型转换 - 其他类型转为数字
alert(parseInt("12")); //12
alert(parseInt("12A45")); //12
alert(parseInt("A45"));//NaN (not a number)

In addition, in js, there is a very important point: 0, null, undefined, "", NaN is understood as false, and vice versa is understood as true. Comment out the previous code and add the following code:

 if(0){
    
     //false
    alert("0 转换为false");
 }

The browser refreshes the page and finds that there is no pop-up box. Because 0 is understood as false, the condition does not hold. Comment out the above code and add the following code:

if(1){
    
     //true
    alert("除0和NaN其他数字都转为 true");
}

The browser refreshes, because 1 is understood as true and the condition is established, so the browser effect is as follows;

Insert image description here

Other situations can be demonstrated one by one. The complete demonstration code is as follows:

    // if(0){ //false
    //     alert("0 转换为false");
    // }
    // if(NaN){//false
    //     alert("NaN 转换为false");
    // }
    if(1){
    
     //true
        alert("除0和NaN其他数字都转为 true");
    }

    // if(""){ //false
    //     alert("空字符串为 false, 其他都是true");
    // }
        
    // if(null){ //false
    //     alert("null 转化为false");
    // }
    // if(undefined){ //false
    //     alert("undefined 转化为false");
    // }

The flow control statements if, switch, for, etc. are consistent with Java and will not be demonstrated here.

**It should be noted that: **In js, 0, null, undefined, "", NaN are understood as false, and vice versa are understood as true

4 functions

In java, in order to improve the reusability of code, we can use methods. Likewise, functions can be used to accomplish the same thing in JavaScript. Functions in JavaScript are designed as blocks of code that perform specific tasks and are defined through the keyword function. Next, let’s learn the two syntaxes for defining functions in JavaScript.

4.1 The first definition format

The first definition format is as follows:

function 函数名(参数1,参数2..){
    
    
    要执行的代码
}

Because JavaScript is a language with weak data types, there are the following points to note:

  • Formal parameters do not need to be declared types, and no matter what type in JavaScript, they are declared by let or var, so it makes no sense to add them.
  • There is no need to declare the type of the return value, just return it directly

Example:

function add(a, b){
    
    
    return a + b;
}

Next we need to write code in VS Code to demonstrate

Step 1: Create a new folder named js, create an html file named 01. JS-function, and then define the function of the above example in <script>:

<script>
     function add(a,b){
      
      
        return  a + b;
     }
</script>

But the above is just a function definition, and the ** function needs to be called to execute! **So next we need to call the function

Step 2: Because the defined add function has a return value, we can accept the return value and output it to the browser. Add the following code:

let result = add(10,20);
alert(result);

Check the browser running results: The content of the browser pop-up box is as shown below:
Insert image description here

4.2 The second definition format

The second method can use var to define the name of the function. The specific format is as follows:

var functionName = function (参数1,参数2..){
    
       
	//要执行的代码
}

Next, we modify the code according to the above format as follows: Just comment out the first definition method and replace it with the second definition method. The function call remains unchanged.

<script>

    //定义函数-1
    // function add(a,b){
      
      
    //    return  a + b;
    // }

    //定义函数-2
    var add = function(a,b){
      
      
        return  a + b;
    }


    //函数调用
    var result = add(10,20);
    alert(result);
    
</script>

The browser pop-up effect is consistent with the above

Insert image description here

When we call the add function, we add two more parameters and modify the code as follows:

var result = add(10,20,30,40);

When the browser is opened, no errors are found, and 30 is still displayed. Why is this?

Because in JavaScript, the function call only needs to have the correct name, and the parameter list does not matter. As in the above case, 10 is passed to variable a, 20 is passed to variable b, and 30 and 40 are not accepted by variables, but it does not affect the normal call of the function.

Guess you like

Origin blog.csdn.net/shenchengyv/article/details/135395459