JavaScript Basics (pink teacher) - day 1

Posted by elfyn on Sat, 05 Feb 2022 04:03:51 +0100

JavaScript Basics (pink teacher) - day 1

1, Introduction

Master the introduction of JavaScript and preliminarily understand the role of JavaScript

1.1 introduction method

JavaScript programs cannot run independently. They need to be embedded in HTML before the browser can execute JavaScript code. There are two ways to introduce JavaScript code into HTML through script tags:

1.1.1 internal form

Wrap JavaScript code with a script tag

1.1.2 external form

JavaScript code is usually written in a separate file js, which is then introduced through the src attribute of the script tag

// demo.js
document.write('Hi, welcome to chuanzhibo to learn front-end technology!');
  <!-- External form: through script of src Property to introduce independent .js file -->
  <script src="demo.js"></script>

!!! If the script tag uses the src attribute to introduce a js file, then the code of the tag will be ignored!!!

1.1.3 inline
<button onclick="alert('click')">Click me</button>

1.2 notes and terminators

You can mask code execution or add comments through comments. JavaScript supports two forms of comment syntax:

Single-Line Comments

Use / / to comment single line code

multiline comment

Annotate multiline code with / * * /

Note: the shortcut key of single line comment in the editor is ctrl +/

Terminator

In JavaScript; Represents the end of a piece of code, which can be omitted in most cases; Use enter instead.

Either all or none

1.3 input and output

1.3.1 output

JavaScript can receive the user's input and then output the input result:

Alert
document.wirte() document
console.log() console output

1.3.2 input

Entering any content into prompt() will appear in the browser in the form of pop-up window, which generally prompts the user to enter some content.

2, Variable

Understand that variables are the "container" of computer stored data, and master the declaration method of variables

Variable is the "container" used to store data in the computer, which can make the computer have memory. Generally speaking, variable is to use [a symbol] to represent [a specific value] (data)

<script>
  // Save the user input in the variable num (container)
  num = prompt('Please enter a number!');

  // Output the user's input through the num variable (container)
  alert(num);
  document.write(num);
</script>

2.1 declaration and assignment

statement

Declaration (definition) variables are composed of two parts: declaration keyword and variable name (identification)

Let and var are both keywords for declaring variables in JavaScript. It is recommended to use let to declare variables!!!

assignment

Declaring (defining) variables is equivalent to creating an empty "container" to which data is added by assignment.

2.2 keywords

JavaScript uses special keywords let and var to declare (define) variables. Some details should be paid attention to when using them:

Here are the precautions when using let:

  1. Simultaneous declaration and assignment are allowed
  2. Duplicate declarations are not allowed
  3. Multiple variables can be declared and assigned at the same time
  4. Some built-in keywords in JavaScript cannot be used as variable names

Here are the precautions when using var:

  1. Simultaneous declaration and assignment are allowed
  2. Allow duplicate declaration
  3. Multiple variables can be declared and assigned at the same time

In most cases, there is little difference between let and VaR, but let is more rigorous than var. therefore, let is recommended. The difference between them will be further introduced later.

2.3 naming rules of variable names

There are a series of rules for variable names (identifiers):

  1. It can only be letters, numbers, underscores and $, and cannot start with numbers
  2. Letters are case sensitive. For example, age and age are different variables
  3. JavaScript internal occupied words (keywords or reserved words) are not allowed
  4. Try to ensure that variables have certain semantics, and see the word to know the meaning

2.4 basic use of array

let Array name = [Data 1, data 2...,data n]

3, Data type

Everything in the computer world is data.

Computer programs can process a large amount of data. In order to facilitate data management, the data are divided into different types:

Note: the data type is detected by the typeof keyword

Thinking questions:

let num = 10
console.log(typeof num + '11')
result: number11
console.log(typeof(num  + '11'))
result: string
console.log(num  + '11')
Result: 1011
console.log(typeof(num + +'11'))
result: number
console.log(num + +'11')
Result: 21

3.1 value type (number)

That is, the numbers we learn in mathematics can be integers, decimals, positive numbers and negative numbers

The numeric type in JavaScript is the same as that in mathematics, which can be divided into positive numbers, negative numbers, decimals, etc.

3.2 String type (String)

Data wrapped in single quotation marks (''), double quotation marks ('') or back quotation marks are called strings. There is no essential difference between single quotation marks and double quotation marks. Single quotation marks are recommended.

matters needing attention:

  1. Both single and double quotation marks must be used in pairs
  2. Single quotation marks / double quotation marks can be nested with each other, but not with themselves
  3. If necessary, you can use the escape character \, and output single quotation marks or double quotation marks

3.3 Boolean type

When it means yes or no, the corresponding data in the computer is boolean type data. It has two fixed values, true and false. The data indicating yes is true and the data indicating no is false.

3.4 undefined

Undefined is a special type. There is only one value undefined, and only variables are declared. In the case of no assignment, the default value of the variable is undefined. Generally, it is rarely [directly] assigned to a variable as undefined.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - data type</title>
</head>
<body>
  
  <script> 
    // Only variables are declared and assigned
    let tmp;
    document.write(typeof tmp); // The result is undefined
  </script>
</body>
</html>

The difference between null and undefined

  1. undefined means there is no assignment
  2. null indicates that the value is assigned, but the content is empty

Note: in JavaScript
The value of a variable determines the data type of the variable.

3.5 template string

//The traditional way is very troublesome
document.write('Hello, my name is' + name + ',this year' + age + 'year')

//When splicing variables, enclose the variables with ${}
document.write(`Hello, my name is ${name},this year ${age}year`)

4, Type conversion

Understand the characteristics of weakly typed languages and master the methods of explicit type conversion

In JavaScript, data is divided into different types, such as numeric value, string, Boolean value and undefined. In the process of actual programming, there is a conversion relationship between different data types.

4.1 implicit conversion

When some operators are executed, the system automatically converts the data type, which is called implicit conversion.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Implicit conversion</title>
</head>
<body>
  <script> 
    let num = 13; // numerical value
    let num2 = '2'; // character string

    // The result is 132
    // The reason is that the numerical value num is converted into a string, which is equivalent to '13'
    // Then + splices the two strings together
    console.log(num + num2);

    // The result is 11
    // The reason is that the string num2 is converted to a numeric value, which is equivalent to 2
    // Then subtract the value 2 from the value 13
    console.log(num - num2);

    let a = prompt('Please enter a number');
    let b = prompt('Please enter another number');

    alert(a + b);
  </script>
</body>
</html>

Note: implicit conversion of data types is a feature of JavaScript and will be encountered in subsequent learning. At present, we need to understand what implicit conversion is.

Supplement the use of template string splicing

4.2 explicit conversion

It is not strictly forbidden to rely too much on implicit conversion inside the system when writing programs, because the law of implicit conversion is not clear, and it mostly depends on the law of experience summary. In order to avoid the problems caused by implicit conversion, the root logic usually needs to display and convert the data.

Number

The Number display is converted to a numeric type. When the conversion fails, the result is NaN (Not a Number), that is, it is Not a Number.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Implicit conversion</title>
</head>
<body>
  <script>
    let t = '12';
    let f = 8;

    // Explicitly convert string 12 to numeric value 12
    t = Number(t);

    // Detect converted type
    // console.log(typeof t);
    console.log(t + f); // The result is 20

    // Not all values can be converted to numeric types
    let str = 'hello';
    // It is unrealistic to convert hello into a value when it cannot be converted into a value
    // When the value is, the result is NaN (Not a Number)
    console.log(Number(str));
  </script>
</body>
</html>

Memorizing word cases

Idea:

  • Outer layer xxx
  • Inner layer xxx
// Memorizing word cases
        // analysis
        // 1. External circulation record day n 
        for (let i = 1; i < 4; i++) {
            document.write(`The first ${i}day <br>`)
            // 2. Record several words in the inner circle
            for (let j = 1; j < 6; j++) {
                document.write(`Remember the first ${j}Words<br>`)
            }
        }

Topics: Javascript Front-end