Basic JavaScript learning

Posted by dinosoup on Fri, 11 Feb 2022 21:32:14 +0100

1, Variable

1. Overview of variables

1.1 what are variables

Vernacular: a variable is a box of things.
Popular: variables are containers for storing data. We get the data through the variable name, and even the data can be modified.

1.2 storage of variables in memory

Essence: a variable is a piece of space applied by a program in memory for storing data.
Similar to hotel rooms, a room can be regarded as a variable.

2. Use of variables

Variables can be used in two steps: 1 Declare variable 2 assignment

2.1 declared variables

//Declare variable
var age; // Declare a variable named age

  • var is a JS keyword used to declare variables (the meaning of variable variable). After using this keyword to declare a variable, the computer will automatically allocate memory space for the variable, which does not need to be managed by the programmer
  • age is the variable name defined by the programmer. We need to access the space allocated in memory through the variable name

2.2 assignment

age = 10; // Assign a value of 10 to this variable

  • =It is used to assign the value on the right to the variable space on the left, which means assignment
  • Variable value is the value that the programmer saves in the variable space

2.3 initialization of variables

var age = 18; // The declared variable is assigned 18 at the same time

Declaring and assigning a variable is called variable initialization.

<!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>variable</title>
    <script>
        // 1. Declare a variable of age
        var age;
        // 2. Assign a value and store it in this variable
        age = 18;
        // 3. Output results
        console.log(age);
        // 4. Initialization of variables
        var myname = 'pink teacher';
        console.log(myname);
    </script>
</head>

<body>

</body>

</html>

2.4 case 1

<!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>Variable case</title>
    <script>
        var myname = 'Qimukakassi';
        var address = 'Huoying Village';
        var age = 30;
        var email = 'kakaxi@itcast.cn';
        var salary = 2000;
        console.log(myname);
        console.log(address);
        console.log(age);
        console.log(email);
        console.log(salary); 
    </script>
</head>

<body>

</body>

</html>

2.5 case 2

<!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>Variable case pop-up user name</title>
    <script>
        // 1. User input name
        var myname = prompt('Please enter your name');
        // 2. Output the user name
        alert(myname);
    </script>
</head>

<body>

</body>

</html>

3. Variable syntax extension

3.1 update variables

After a variable is re assigned, its original value will be overwritten, and the value of the variable will be subject to the last assigned value.

3.2 declare multiple variables at the same time

When declaring multiple variables at the same time, you only need to write a var, and the names of multiple variables are separated by English commas.

3.3 special cases of declared variables


Tip: after the program reports an error, the following code will not be executed.

4. Variable naming specification


Tip: name is not a keyword or reserved word, but it generally has special meaning in some browsers, so it's best not to use this word for variable names.

5. Case - exchange two variable values

Requirements: exchange the values of two variables (implementation idea: use a temporary variable as intermediate storage)

<!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>Swap two variable values</title>
    <script>
        // js is a programming language with strong logic in it; The idea of realizing this requirement is how to do it first and then how to do it
        // 1. We need a temporary variable to help us
        // 2. Give us the temporary variable temp from apple1
        // 3. Give the apple in apple2 to apple1
        // 4. Give the value in the temporary variable to apple2
        var temp; //A temporary variable was declared null
        var apple1 = 'green apple';
        var apple2 = 'Red apple';
        temp = apple1; //Assign the value of the right to the left
        apple1 = apple2;
        apple2 = temp;
        console.log(apple1);
        console.log(apple2);
    </script>
</head>

<body>

</body>

</html>

6. Summary

2, Data type

1. Introduction to data types

1.1 why do you need data types

In the computer, the storage space occupied by different data is different. In order to divide the data into data with different memory sizes and make full use of the storage space, different data types are defined.

1.2 data types of variables

Variables are where values are stored. They have names and data types. The data type of the variable determines how the bits representing these values are stored in the computer's memory. JavaScript is a weakly typed or dynamic language. This means that there is no need to declare the type of variable in advance, and the type will be determined automatically during the operation of the program.

var age = 10; // This is a numeric type
var areYouOk = 'yes'// This is a string

When the code is running, the data type of the variable is determined by the JS engine according to the data type of the variable value on the right. After running, the variable determines the data type.
JavaScript has dynamic types, which also means that the same variables can be used as different types:

var x = 6; // x is a number
var x = ‘Bill’; // X is a string

1.3 classification of data types

JS divides data types into two categories:

  • Simple data type (Number, String, Boolean, Undefined, Null)
  • Complex data type (Object)

2. Simple data type

2.1 simple data type (basic data type)

Simple data types in JavaScript and their descriptions are as follows:

2.2 digital Number

The JavaScript number type can be used to hold both integer values and decimals (floating point numbers).

var age = 21; // integer
var Age = 21.3747 / / decimal

2.2.1 digital hexadecimal

The most common base systems are binary, octal, decimal and hexadecimal.

2.2.2 digital range

Maximum and minimum values of values in JavaScript

alert(Number.MAX_VALUE); // 1.7976931348623157e+308
alert(Number.MIN_VALUE); // 5e-324

2.2.3 three special values of digital type


<!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>Digital type Number</title>
    <script>
        var num = 10; // num numeric
        var PI = 3.14; // PI digital type
        // 1. Octal 0 ~ 7 in our program, adding 0 in front of numbers means octal
        var num1 = 010;
        console.log(num1); // 010 octal to hexadecimal is 8
        var num2 = 012;
        console.log(num2); // Output 10
        // 2. Hex 0 ~ 9 a ~ f 
        var num3 = 0x9;
        console.log(num3); // Output 9
        var num4 = 0xa;
        console.log(num4); // Output 10
        // 3. Maximum value of digital type
        console.log(Number.MAX_VALUE);
        // 4. Minimum value of digital type
        console.log(Number.MIN_VALUE);
        // 5. Infinity
        console.log(Number.MAX_VALUE * 2); // Infinity infinity
        // 6. Infinitesimal
        console.log(-Number.MAX_VALUE * 2); // -Infinity infinitesimal
        // 7. Non numeric
        console.log('pink teacher' - 100); //NaN non numeric
    </script>
</head>

<body>

</body>

</html>

2.2.4 isNaN()

It is used to judge whether a variable is of non numeric type and returns true or false

var userAge = 21;
console.log(isNaN(userAge)); // false, 21 is not a non number
var userName = 'andy';
console.log(isNaN(userName)); // true, 'andy' is non numeric

2.3 String type String

A string can be any text in quotation marks, and its syntax is double quotation mark '' and single quotation mark ''

Because the attributes in HTML tags use double quotation marks, we prefer to use single quotation marks in JS.

2.3.1 string quotation mark nesting

JS can nest double quotation marks with single quotation marks, or nest single quotation marks with double quotation marks (outer single, inner double, outer double, inner single)

2.3.2 string escape character

Similar to the special characters in HTML, there are also special characters in the string, which we call escape characters.
The common escape characters and their descriptions are as follows:

Tip: the escape character must be enclosed in quotation marks

2.3.3 case: pop up Web warning box

<!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>Pop up Web alert box</title>
    <script>
        alert('Under the hot sun, my tall and straight posture has become the most unique scenery. I look around, here is my stage, I am the king of heaven and earth.\n At this moment, I was so proud that I finally shouted, "collect the rags~"');
    </script>
</head>

<body>

</body>

</html>

2.3.4 string length

A string is composed of several characters. The number of these characters is the length of the string. The length of the whole string can be obtained through the length attribute of the string.

var strMsg = 'I'm a handsome and rich programmer!';
alert(strMsg.length); // Display 11
var str = 'my name is andy';
console.log(str.length); // Output 15

2.3.5 string splicing

  • After the string is spliced, it can be spliced with any string type of + string
  • Before splicing, any type added with the string will be converted into a string, and then spliced into a new string

    +Number summary formula: numerical values are added and characters are connected

2.3.6 string splicing reinforcement

  • We often splice strings and variables, because variables can easily modify their values
  • Variables cannot be quoted because quoted variables will become strings
  • If there is string splicing on both sides of the variable, the formula "quote plus", delete the number and write the variable in the middle

2.3.7 case: display age

An input box pops up, requiring the user to enter the age, and then a warning box pops up to display "you are xx years old" (xx indicates the age just entered)
This is a very simple interactive effect program written with JS.

<!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>Case: display age</title>
    <script>
        var age = prompt('Please enter your age');
        var str = 'You this year' + age + 'Years old';
        alert(str);
    </script>
</head>

<body>

</body>

</html>

2.4 Boolean

Boolean types have two values: true and false, where true represents true (true) and false represents false (false).
When Boolean and numeric types are added, the value of true is 1 and the value of false is 0.

console.log(true + 1); // 2
console.log(false + 1); // 1

2.5 Undefined and Null

A variable that has not been assigned a value after declaration will have a default value of undefined (pay attention to the result when connecting or adding)

A declared variable is given a null value, and the value stored in it is null (when learning objects, we continue to study null)

3. Get variable data type

3.1 get the data type of the detection variable

typeof can be used to obtain the data type of the detection variable

<!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>Gets the data type of the variable</title>
    <script>
        var num = 10;
        console.log(typeof num); //number
        var str = 'pink';
        console.log(typeof str); //string
        var flag = true;
        console.log(typeof flag); //boolean
        var vari = undefined;
        console.log(typeof vari); //undefined
        var timer = null;
        console.log(typeof timer); //object
        // The value from prompt is a character string
        var age = prompt('Please enter your age');
        console.log(age);
        console.log(typeof age);
    </script>
</head>

<body>

</body>

</html>


Tip: we can also judge the data type by the color output from the browser console, chrome. Black is character type, blue purple is numeric type, dark blue is boolean type, and gray is undefined or null type

3.2 literal quantity

We know what value it is at a glance, which is called literal quantity.

4. Data type conversion

4.1 what is data type conversion

The data obtained by using form and prompt is of string type by default. At this time, you can't simply add directly, but need to convert the data type of the variable. Generally speaking, it is to convert a variable of one data type into another data type.
We usually realize the conversion in three ways:

  • Convert to string type
  • Convert to numeric type
  • Convert to Boolean

4.2 convert to string

  • toString() and String() are used differently.
  • Among the three conversion methods, we prefer the third plus sign splicing string conversion method, which is also called implicit conversion
<!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>Convert to character</title>
    <script>
        // 1. Convert numeric variables to string variables toSring()
        var num = 10;
        var str = num.toString();
        console.log(str);
        console.log(typeof str);
        console.log(typeof num);
        // 2. Use string (variable)
        console.log(String(num));
        // 3. Use the method of + splicing string to realize the implicit conversion of conversion effect
        console.log(num + '');
    </script>
</head>

<body>

</body>

</html>

4.3 conversion to digital type (key)

  • Pay attention to the case of parseInt and parseFloat words, which are the key points
  • Implicit conversion is that JS automatically converts data types when we perform arithmetic 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>Convert to digital</title>
    <script>
        var age = prompt('Please enter your age');
        console.log(age); //The result is a string value
        // 1. ParseInt (variable) can convert string type to numeric type, and the result is an integer
        console.log(parseInt(age)); //Conversion of string type to number type
        console.log(parseInt('3.14')); // 3 rounding
        console.log(parseInt('3.14')); // 3 rounding
        console.log(parseInt('120px')); // 120 will remove this px unit
        console.log(parseInt('rem120px')); // NaN non numeric
        // 2. Parsefloat (variable) can convert string type to number type, and get decimal floating point number
        console.log(parseFloat('3.14')); // 3.14
        console.log(parseFloat('120px')); // 120 will remove this px unit
        console.log(parseInt('rem120px')); // NaN
        // 3. Use number (variable)
        var str = '123';
        console.log(Number(str));
        // 4. Arithmetic operation - * / implicit conversion is used
        console.log('12' - 0); // Digital 12
        console.log('123' - '120'); // 3
        console.log('123' * 1); // Digital 123
    </script>
</head>

<body>

</body>

</html>

4.4 case 1: calculating age

This case requires an input box to pop up in the page. After we enter the year of birth, we can calculate our age.

<!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>Calculate age case</title>
    <script>
        var year = prompt('Please enter your year of birth');
        var age = 2022 - year; // year takes the string type, but the subtraction used here has implicit conversion
        alert('You have this year' + age + 'Years old');
    </script>
</head>

<body>

</body>

</html>

4.5 case 2: simple adder

Calculate the value of two numbers. After the user enters the first value, continue to pop up the second input box and enter the second value. Finally, the result of adding the two input values is displayed through the pop-up window.

<!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>Case 2: simple adder</title>
    <script>
        var num1 = prompt('Please enter the first value:');
        var num2 = prompt('Please enter the second value:');
        var result = parseFloat(num1) + parseFloat(num2);
        alert('The result of the addition is:' + result);
    </script>
</head>

<body>

</body>

</html>

4.6 convert to Boolean

3, Expand reading

1. Interpretive language and compiled language


2. Identifier, keyword and reserved word

2.1 identifier

Identifier: the name given by the developer for variables, attributes, functions and parameters.
Identifiers cannot be keywords or reserved words.

2.2 keywords

Keyword: refers to the words already used by JS itself, which can no longer be used as variable name and method name.
Including: break, case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with, etc.

2.3 reserved words

Reserved words: actually reserved "Keywords", which means that although they are not keywords now, they may become keywords in the future. Similarly, they cannot be used as variable names or method names.

Homework after class

Ask and obtain the user's name, age and gender in turn, and print the user information

<!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>Homework after class</title>
    <script>
        var userName = prompt('Please enter your name:');
        var age = prompt('Please enter your age:');
        var sex = prompt('Please enter your gender:');
        alert('Your name is:' + userName + '\n' + 'Your age is:' + age + '\n' + 'Your gender is:' + sex);
    </script>
</head>

<body>

</body>

</html>


Tip: the escape character must be enclosed in quotation marks

Topics: Javascript