JS Basic Tutorial

1. Introduction to JS

1.1 Learning content

JavaScript ("JS" for short) is a lightweight, interpreted or just-in-time compiled programming language with function priority. It is famous as a scripting language for developing Web pages. JavaScript is based on prototype programming, a multi-paradigm dynamic scripting language, and supports object-oriented, imperative, declarative, and functional programming paradigms.

  • ECMAScript, which describes the syntax and fundamental objects of the language.
  • The Document Object Model (DOM), which describes methods and interfaces for working with web content.
  • The Browser Object Model (BOM), which describes the methods and interfaces for interacting with the browser.

1.2 Features

  • interpreted language
  • Syntax structure similar to C and Java
  • dynamic language
  • prototype-based object-oriented

2. Basics of getting started 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>Document</title>
    <script type="text/javascript">
        alert(" 这是一个警告框");
        document.write("这是一个文档");
        console.log("在控制台输出");
    </script>
</head>
<body>
</body>
</html>

The effect is as follows

Among them, the output effect in alert(" ") is a warning box, click OK to continue to execute the webpage style
document.write(""), document means to output a document, and write means to write materials in the document.
console.log("" ) means to enter the corresponding material in the console

Three, JS external reference

Note: JS references may not be successful in general, you can put the html file and the js file in the same folder

3.1 JS references are the same as CSS references

  • JS references are in the format of JS: script
  • In Script, if the Script has used the external reference style, other styles in the Script tag will not be available

3.2 How to use

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

./script.js is the written file

4. JS Basics - Grammar

  • Strictly case-sensitive in JS
  • Each statement in JS ends with a semicolon (;)

If you do not write a semicolon, the browser will add it automatically, but it will consume the system resources of the browser. At the same time, sometimes, the browser will add the wrong semicolon, so you must write the semicolon in the development

  • Multiple spaces and newlines are ignored in JS, so we can use spaces and newlines to format the code

5. JS Basics - Literals and Variables

5.1 Literal values: they are all unchangeable values

  • For example: 1 2 3 4 5
  • Literal quantities can generally be used directly, but we generally do not use literal quantities directly

5.2 Variables: Variables can be used to store literals, and the value of variables can be changed arbitrarily

  • Variables are more convenient for us to use, so in development, variables are used to save a literal and rarely use literals directly
  • declare variable

Using the var keyword in JS to declare a variable
is as follows:

    <script>
        var a;
        a=16;
        var b=32;
        var age=56;
    </script>
  • You can define and identify a variable a in two paragraphs, or you can use only one paragraph such as var b=32;
  • var can use a letter to define a variable, or a word such as age, weight, etc., so that you can clearly see what the variable represents when the following program is running

6. JS Basics - Identifier

6.1 Identifiers

In JS, everything that can be named by us can be called an identifier. For example: variable names, function names, and attribute names are all identifiers.

identifier rules

  • Identifiers can contain: letters, numbers, _, $
  • Identifier cannot start with a number
  • Identifiers cannot start with keywords or reserved words in ES
  • Identifiers generally use camel case

The first letter is lowercase, the letter at the beginning of each letter is uppercase, and the rest of the letters are lowercase, such as helloWorld xxxYyyZzz
JS underlying storage identifier is actually Unicode encoding, so theoretically speaking, all the content contained in utf-8 can be used as an identifier characters, Chinese can also be used as identifiers, but generally do not use Chinese as identifiers

Seven, JS basics - string

7.1 The data type refers to the literal type

There are six types of data types in JS

  • String string
  • Number value
  • Boolean Boolean value
  • Null
  • Undefined undefined
  • Object object

7.2 Each data type

  1. String string

Strings in JS need to be enclosed in quotation marks.
You can use single quotation marks or double quotation marks, but don’t mix them.
Quotation marks cannot be nested.

The solution that quotation marks cannot be nested

  • Change the outermost quotes to double quotes
<script>
        str='我说:"这是一个段落"';
        alert(str);
    </script>
  • Prepend quotes with translation tags
    <script>
        str="我说:\"这是一个段落\"";
        alert(str);
    </script>
  1. Number value
  • All values ​​​​in JS are Number types
    , including integers and floating point numbers (decimals)

  • The maximum and minimum values ​​of numbers that can be represented in JS

var b=Number.MAX_VALUE;
var c=Number.MIN_VALUE;

Among them, the maximum value is Number.MAX_VALUE with a value of 1.7976931348623157e+308 and
the minimum value is Number.MIN_VALUE with a value of 5e-324 (minimum greater than zero).
If the value represented by Number exceeds the maximum value, an Infinity will be returned

As shown below, the size of b is defined as the square of a maximum value

<script> 
        var b=Number.MAX_VALUE*Number.MAX_VALUE;
        alert(b);
    </script>
  1. An error occurred when multiplying Numbers. When
    two characters were multiplied together, the result could not be obtained. The result obtained by the program was NaN.
<script> 
        a="af"*"wfhni";
        alert(a);
    </script>

NaN is a special number that means Not A Number
Use typeof A Checking for a NaN will also check
How to check using typeof?

var a=2312;
console.log(typeof a);

var a="WFA";
console.log(typeof a);

  1. Operations
    in JS Integer operations in JS can basically guarantee accuracy, but sometimes some abnormal errors may occur,
    so do not use JS for calculations with relatively high accuracy.

  2. Boolean Boolean value
    There are only two Boolean values, which are mainly used to logically judge
    true-means true
    false-means false

var bool=true;
console.log(typeof bool);

  1. Null There
    is only one value of the Null type, which is Null
    Null is specially used to represent an empty object
    When using typeof to check a Null value, it will return object

  2. Undefined There
    is only one value of the Undefined type, which is undefined.
    When a variable is declared but no value is assigned to the variable, its value is undefined

8. JS Basics - Mandatory Type Conversion

8.1 Convert other data types to String

Method 1: Call the toString() method of the converted data type

var a=13

Call the toString() method of a
Call the yyy() method of xxx, which is xxx.yyy()

var a=42;
var b=a.toString();
console.log(a);
console.log(typeof a);
console.log(b);
console.log(typeof b);

This method will not affect the original variable, it will return the result of the conversion

It can be seen that the values ​​of a and b are both 42, but the data type of a is normal and is number; the data type of b is string,
and a can be directly converted into a string type, as shown below:

var a=42;
a=a.toString();
console.log(a);
console.log(typeof a);

But note: the two values ​​​​null and undefined do not have toString() methods. If you call their methods, an error will be reported

Method 2: Call the string() function and pass the converted data to the function as a parameter

  • Calling the xxx function is generally the xxx function
  • For example, calling the string function is String()
  • Calling the alert function is alert()
a=null;    
a=String(a);
console.log(a);
console.log(typeof a);

When using the String() function for mandatory type conversion

For Number and Boolean, the toString() method is actually called, but for null and undefined, the toString() method will not be called: he will directly convert null to "null" and undefined directly to "undefined"

8.2 Convert other data types to Number

Method 1: Use the Number() function
to call the Number function to convert a to a Number type

If it is a string of pure numbers, convert it directly to a number

var a=123;
a = Number(a);
console.log(typeof a);      

If there is non-numeric content in the string, it will be converted to NaN

var a=abc
a=Number(a);
console.log(typeof a);
console.log(a);

Converts to 0 if the string is an empty string or a string full of spaces

Boolean → number, true to 1, false to 2
Null → number 0
undefined → number NaN

This method has flaws, such as a = "123px" cannot be expressed

Method 2: This method is specially used to deal with strings

parseInt() converts a string to an integer (int integer)

parseInt() can take out the valid integer content in a string, and then convert it to Number.
Example
1

a = "123.456px";
a = parseInt(a);
document.write(a);


As shown in Example 1, all numbers after the decimal point are ignored
Example 2

b = "789ald95px";
b = parseInt(b);
document.write(b);


As shown in Example 2, the letters and the numbers after the letters are all ignored

parseFloat() converts a character into a floating point number (float floating point number)
parseFloat() is similar to parseInt(), but it can get valid decimals

a = "123.456.789px";
a = parseFloat(a);
document.write(a);

As shown in the example, a = "123.456.789px uses parseFloat() to output 123.456 because the following .789 is an invalid decimal value

If you use parseInt() or parseFloat() on a non-String, it will first convert it to a String before manipulating

8.3 Representing other bases in JS

For hexadecimal numbers, it needs to start with 0x (zero X)
For octal numbers, it needs to start with 0 (zero)

a = "070" as an example, some browsers will parse it as decimal 70, and some browsers will parse it as octal number
In order to solve this problem, you can pass a second parameter in parseInt() : a = parseInt(a,10) The 10 in this style means to convert a to decimal.
In fact, octal is generally not used, so try to avoid this kind of writing with 0 in front of the number

Represents a binary number, starting with 0b (zero b) {but not all browsers support binary}

8.4 Convert other data types to Boolean

Use the Boolean() function

var a = 123;
a = Boolean(a);
console.log(typeof a);
console.log(a);

For numbers, except 0 and NaN, the rest are true
For strings, except for empty strings, the rest are true
null and undefined will be converted to false

Object also converts to true

Nine, JS basics - arithmetic operators

9.1 Introduction

Operators are also called operators, through which operators can operate on one or more values
​​For example: typeof is an operator, which can be used to obtain the type of a value. typeof a; can help us get the type of a, it will return the type of the value as a
string number string boolean undefined object

9.2 Arithmetic operators

When operations are performed on values ​​of non-Number types, these values ​​are converted to Number and then operated on

+  
-
*
/
%

9.2.1 + operator

  • + can add two values ​​and return the result.
  • If the addition operation is performed on two strings, it will do string concatenation, that is, concatenate the two strings into one string and return it.
    Any value added to a string will be converted to a string first and then combined with the string

Example
(1) Number addition

var a = 123
a = a + 456 
document.write(a)

(2) String addition

var a = "123";
a = a + "456" ;
document.write(a);
var a = 123;
a = a + "jiaozhu" ;
document.write(a);
var a = "nanfang";
a = a + "jiaozhu" ;
document.write(a);

We can take advantage of this feature to convert an arbitrary data type to a String.
We only need to add a "" to any data type to convert it to a String.
This is an implicit type conversion, which is automatically performed by the browser. Complete, in fact it is also the String() function called

9.2.2 - Operators

You can subtract two values ​​and return the result

9.2.3 * operator

Can perform multiplication of two values

9.2.4 The / operator

Can perform division operation on two values

Any value-subtraction multiplication/division will be automatically converted to Number.
We can use this feature to do implicit type conversion.
It can be converted to Number by a value -0
1/1. The principle is the same as the Number() function. simpler

9.2.5 % operator

Modulo operation (remainder)

10. JS Basics - Unary Operators

Unary operators: only one operand is required

  • The positive sign
    happens to have no effect on the number
  • Negative sign The negative sign can reverse the negative sign of the number
    . For the value of non-Number type,
    it will convert the value to Number first, and then operate.
    You can use + to convert it to number for another data type.
    Its principle Same as Number() function

Eleven, JS basics - auto-increment and auto-decrement

Increment:

  • By self-increment, the variable can be increased by 1 on its own basis
  • After a variable is incremented, the value of the original variable is incremented by 1 immediately
  • There are two types of self-increment: post ++ and pre ++ (ie a++ and ++a)
  • Whether it is a++ or ++a, the value of the original variable will be incremented by 1 immediately
  • The difference is that the values ​​​​of a++ and ++a are different

The value of a++ is equal to the value of the original variable
++ The value of a is equal to the value of the original variable after increment

Decrement

  • The variable can be reduced by one on its own basis by self-decrement
  • Decrement has also been divided into two types: post- and pre-

Whether it is a– or –a, it will immediately increase the value of the original variable by 1, the difference is that the values ​​​​of a– and –a are different

  • a– is the original value of the variable (value before self-decrement)
  • –a is the new value of the variable (the value since the decrement)

12. JS Basics - Logical Operators (Boolean Series)

We provide three logical operators in JS

  • ! :No

! It can be used to negate a value.
The so-called negation is the negation of a Boolean value,
true becomes false, and false becomes true
. If a value is negated twice, it will not change.
If a non-Boolean value is performed operation, it will be converted to a Boolean value, and then reversed.
So we can use this feature to convert another data type to a Boolean value. We
can reverse any integer data type twice to convert it to The principle of Boolean value
is the same as Boolean()

  • && :and

&& can perform an AND operation on the values ​​that match both sides and return the result.
If both are true, the result will return true
. As long as there is one false, the result will return false.

If the first value is true, the second value is checked
If the first value is false, the second value is not checked

  • || or

|| can perform an OR operation on the values ​​on both sides of the symbol and return the result
Operation rules:
as long as one of the two values ​​is true, it will return true;
if both values ​​are false, it will return false

In JS or short-circuit or
the first value is false, then continue to check the second value, if the first value is true, it will not continue to check the second value

12. JS Basics - AND OR Operation of Non-Boolean Values

When performing an AND or operation on a non-Boolean value, it will be converted to a Boolean value, then operated, and the original value will be returned

  • And calculation
    If the first value is true, the second value must be returned
    If the first value is false, the first value will be returned directly
    For example
var a = 3 && 4;
console.log("a = " + a);

  • OR operation
    If the first value is true, return the first value directly
    If the first value is false, return the second value directly
var a = 3 || 4;
console.log("a = " + a);

12. JS Basics - Assignment Operator

You can assign the value on the left side of the symbol to the variable on the left side of the symbol
Example:

var a = 10 ,b = 12;
a = a + 5;
b  += 1 ;
console.log(a)
console.log(b)

It can be seen from the example;

a += 5等价于 a = a + 5
a -= 5等价于 a = a - 5
a *= 5等价于 a = a * 5
a %= 5等价于 a = a % 5

Thirteen, JS basics - relational operators

  • In the case of numerical values,
    the relational operator can compare the size relationship between two values.
    If the relationship is established, it will return true, and if the relationship is not established, it will return false.

Greater than
sign Determine whether the value on the left side of the symbol is greater than the value on the right side
If the relationship is established, return true, if the relationship is not established, return false

var a = 5 > 10
console.log("a ="+a)

greater than or equal >=
less than <
less than or equal to <=

  • non-numeric case

Strings are compared with general numbers
Examples are as follows

var a = 2 > true
console.log("a ="+a)
var b = 1 > true
console.log("b ="+b)

Among them, true is calculated as 1 here,
and any comparison between any value and NaN is false

If the values ​​on both sides of the symbol are strings, they will not be converted to numbers for comparison, but the Unicodes of the characters in the strings will be compared separately

  • When comparing strings, the character encodings of the strings are compared
  • When comparing character codes, it is compared one by one
  • If the two bits are the same, compare the next bit, so you can borrow it to sort the English letters
  • Doesn't make sense when comparing Chinese
  • If you compare two string-type numbers, you may get unexpected results (note: when comparing two string-type numbers, you must transform)

14. JS Basics - Unicode Encoding

Unicode encoding is the encoding of most texts, including various English, Chinese, Oracle, German, French, Arabic and even special symbols such as ☠

Enter the Unicode encoding in the script tag
For example: console.log("\u2620")

Starting with the translation character \u, you can add Unicode translation characters to some elements in the script. As in the above example, the ☠ symbol that usually does not appear can appear

Use Unicode encoding encoding in web pages
; the encoding here needs to be decimal, and the original Unicode encoding is hexadecimal.
The example is as follows:
<h1>&#9760</h1>

If you want to use Unicode encoding inside the webpage (body), you need to use a calculator to manually convert it to decimal before compiling

15. JS Basics - Equality Operator

15.1 Equality Operators

var a = 4;
console.log( a == 10);

  • Here, a == 10 is used to represent equal comparison, and equal is ==, which must be represented by two equal signs next to each other. Returns true if equal, false otherwise
  • When using == to compare two values, if the values ​​are of different types, type conversion will be performed automatically, converting them to the same type, and then comparing
  • NaN is not equal to any value, including itself

That is, var a = NaN; console.log( a == NaN);the return result is false

You can use the isNaN() function to check whether a value is NaN

var a = NaN;
console.log( a == NaN);
console.log(isNaN(a))

The isNaN() function returns true if the value is NaN, otherwise returns false

15.2 Inequality Operators

Used to determine whether two values ​​are not equal, if not equal return true, otherwise return false

  • Inequality symbol: !=
    Not equal will also perform automatic type conversion on the variable, if it is equal after conversion, it will also return false

  • Congruence: ===
    is used to judge whether two values ​​are congruent, it is similar to equality, the difference is that it does not perform type conversion

  • Not equal: !==
    is used to judge whether two values ​​are not equal, similar to inequality, the difference is that it does not perform automatic type conversion. If the two values ​​are of different types, return true directly

Sixteen, JS basics - conditional operators

  • Conditional operator
    Conditional operator is also called ternary operator

  • Syntax:
    Conditional expression? Statement 1: Statement 2;

  • Execution process:
    When the conditional operator is executed, it first evaluates the conditional expression.
    If the value is true, statement 1 is executed and the execution result is returned.
    If the value is false, statement 2 is executed and the execution result is returned.
    If If the result of the conditional expression is a non-Boolean value, it will be converted to a Boolean value before operation

Example principle

true?alert("语句1"):alert("语句2");

As shown above, execute statement 1

actual use

var a = 124 , b = 213;
a>b?alert("a大"):alert("b大");

You can make a judgment first, and then output

Another way to get the maximum value of a and b (another ternary operator)
to compare the size of a and b

var max = c > d ? c : d;

Among them, c > d? Enter the conditional operation, c : d compare the two, and finally assign the maximum value to max (var max =)

Select the maximum value among a, b, c,
Method 1

var max = a > b ? a : b;
max = max > c ? max :c;

First compare a, b, respectively, then take the maximum value of a, b, and compare it with c, and finally output the maximum value

Method Two

var max = a > b ? a > c ? a : b : c > c ? b : c;

(var max = a > b ? ( a > c ? a : c ) : (b > c ? b : c);)

This way of writing is not recommended: it is not convenient to read

Guess you like

Origin blog.csdn.net/qq_32907491/article/details/131742656