The initial JavaScript

JavaScript language creator: Brandon Edge.

JavaScript is one of the most popular languages in the world. It is a scripting language that runs on the client side.

Scripting language: no compilation is required, the JS interpreter (JS engine) interprets and executes line by line during execution

Server-side programming is now also possible based on Node.js technology

The role of JavaScript

Form verification web special effects server development (Node.js) desktop application APP game development, etc.

HTML/CSS/JS relationships:

HTML/CSS is a markup language — a description class language.

Javascript scripting language – Programming class language – programming language

Browser executes JS

The browser is divided into two parts: rendering engine and JS engine

JS engine: also called JS interpreter. It is used to read JavaScript code from a web page, process it and run it, such as Chrome V8

The browser itself does not execute JS code. Instead, the code is executed through a built-in JS engine. The JS engine interprets each line of source code line by line when executing the code, and then the computer executes it, so JavaScript language is classified as a scripting language, which will explain the execution line by line.

The composition of JS

  • ECMAScript(which specifies the basic syntax of JS)
  • The DOM Document Object model provides tools for manipulating HTML documents
  • The BOM browser object model provides tools for manipulating the browser

Js writing position

Three writing positions: inline inline chain

We recommend double quotes in HTML and single quotes in JS.

The inline type

We can put JS code inside the tag, and the event attribute is onclick

<! <button onclick="alert(' love you ')"> </button>Copy the code

embedded

You need to create a new tag in your HTML code, preferably before the closing tag

<script> alert(' Wait for you in the rain ') </script>Copy the code

Outside the chain

You need to put the JS code in a JS file whose extension must end in.js. You need to introduce the script tag in the HTML tag, via the SRC attribute of the script tag

Step 1: Create a new.js file

Step 2: Introduce via the SRC attribute of the script tag

 
<script src="./index.js"></script>
Copy the code

Note:

  1. An HTML file can import multiple JS files
  2. A pair of script tags can implement only one way of writing at a time

Js annotation

  • Single-line comment CTRL +/

    // The contents of the commentCopy the code
  • The default shortcut for multi-line comments is Shift + Alt + A, which can be changed to CTRL + Shift + / in VSCode

    Vscode → Preferences button → Keyboard shortcut → Find the old shortcut key → change to a new shortcut key → Enter to confirm

    /* The contents of the comment */Copy the code

Js input and output statements

  • The input statement

    Prompt (), which pops up an input dialog to the browser, doesn’t do much

    // Enter the statement prompt(' Please enter your age ')Copy the code
  • Output statements

    An alert box that pops up an alert to the browser is less used

    Console.log (‘ content ‘) outputs the content log to the console TAB in the browser’s developer tools

    Document.write (‘ output ‘) outputs content to the body tag, which can be an HTML tag

    // Alert (' I pop out ') console.log(' I pop out from the console '); //document document write: write document.write(' output content ') document.write('<h1> title tag </h1>')Copy the code

Statement terminator (supplement)

If only one statement is written in a js line, a semicolon (;) or no semicolon (;) can be added to the end of the statement

If there are multiple statements in a line, a semicolon (;) must be added to the end of each statement. Otherwise, an error message is displayed.

There is hardly any code that writes more than one JS statement in a single line

alert('hello') alert('world'); / / an error alert (' hello '); alert('world'); / / rightCopy the code

Js – Variables (important)

Variable concept

In plain English: VARIABLES are boxes for things.

Popular: variables are containers used to hold data. Data can be retrieved from variables and can also be modified.

Essence: A variable is a block of memory that a program requests to store data

Use of variables

  • Declare a variable
  • Variable assignment

Create a variable

The first way:

Declare variables first, then assign values

var age; // declare variable age = 18; // Assign the variable name ageCopy the code

The second way:

Assigning a value at the same time as declaring a variable is called an initialization of the variable

var age = 20; // Initialize the variableCopy the code

When creating a variable, always add the var keyword

Use the variable

Like output variables

Variable case pops up user name

Use variables to hold data entered by the user

<! Var data = prompt(" please enter your name :") alert(data) </script>Copy the code

Variable syntax extension

  • Variable syntax extension – Updates variables
  • When a variable is reassigned, its original value is overwritten, and the value of the variable is the last value assigned.
Var uname = 'console.log' (uname); Uname = 'lee' console.log(uname);Copy the code
  • Variable syntax extension – Declare multiple variables
  • To declare multiple variables at the same time, write only one var and separate the variable names with commas (,).
Var uname = 'c ', age = 18, address =' console.log '(uname,age,address);Copy the code
  • Note the importance of declaring variables
Var age console.log(age); // undefined // console.log(MyName); // undefined // console.log(MyName); // MyName is not defined // Uname = 'three' console.log(uname); // However, an error is reported in strict js mode,Copy the code
  • Js strict schema (supplement)
Es5 'use strict' uname = 'three' console.log(uname) // Error uname is not defined // When you're defining variables, make sure you add varCopy the code

Variable naming conventions

  1. The value consists of letters (A-zA-z), digits (0-9), underscores (_), and dollar signs ($), for example, usrAge, num01, and _name
  2. Strictly case sensitive. var app; And var App; Is two variables
  3. You can’t start with a number. 18age is wrong
  4. The value cannot be a keyword or reserved word. For example: var, for, while
  5. Variable names must make sense. MMD BBD NL → age
  6. Follow the hump nomenclature. The first letter should be lowercase. The first letter of the following words should be capitalized. myFirstName
  7. Recommended translation website: Youdao Iciba

An error

If there is an error on the previous line, none of the following code will be executed

console.log(MyName); Var uname = 'James' console.log(uname); // Uname is not defined.Copy the code

Swap the values of two variables

/ / exchange to the value of the variable / 2 * 1.1 * / to create two variables var apple1 = 'green apple'/var/left hand apple2 = 'red apple / / hand / * 1.2 declare a temporary variable is empty * / var/temp/bench / * 1.3 I'm going to give the left hand apple to the temp variable so that the left hand is free */ temp = Apple1 /* 1.4 I'm going to give the right hand apple to the left hand so that the right hand is free */ apple1 = Apple2 /* 1.5 I'm going to give the right hand apple */ Apple2 = temp console.log(apple1); // Red Apple console.log(apple2); // Apple console.log(apple1,apple2); // Multiple variables can be printed at the same time, separated by commas.Copy the code

Data type (critical)

Cars are classified in real life, trucks, buses.

Data: numbers, Chinese and so on. It is convenient for JS language to manage it.

But JS is a weakly typed scripting language.

Weak type: when declaring a variable, we do not need to specify the type of the variable, but our JS variable also has a type, but its type is determined by the value of the variable.

Strongly typed: When declaring a variable, always specify the type of the variable

It is efficient for strongly typed languages and inefficient for weakly typed languages. The built-in parser in JS that says what type of variable are we declaring

JS classifies data types into two categories:

  • Simple data types (Number, String, Boolean, Undefined, Null)
  • Complex Data Types (Objects)

Basic data types: a variable can hold only one value

Complex data types: A variable can hold multiple values

Basic data types: Number, String, Boolean, undefined, null

Digital type Number

The values of the variable include: number, NaN

  • Maximum and minimum values for numeric values in JavaScript
alert(Number.MAX_VALUE); / / 1.7976931348623157 e+308 alert (Number. MIN_VALUE); // 5e-324Copy the code
  • Numeric type with three special values
 
alert(Infinity); // Infinity
alert(-Infinity); // -Infinity
alert(NaN); // NaN
Copy the code

Infinity, Infinity, greater than any number Infinity, less than any number NaN, Not a number, a non-number

typeof

Used to check the data type of a variable

Var num = 10 var num1 = NaN var res = typeof num1 console.log(res);Copy the code

isNaN()

Used to determine whether a variable is of a non-numeric type and returns true or false

var number = 10; console.log(isNaN(number)); Var number1 = "three Kingdoms "; console.log(isNaN(number1)); // trueCopy the code

String String

A string can be any text in quotes. The syntax is double “” or single “”, but single quotes are recommended.

A variable is a string as long as its value is enclosed in quotation marks (single and double quotation marks), regardless of what is inside the quotation marks.

var str = '1234'; console.log(typeof res); / / type StringCopy the code

Note: string type = needs to be quoted, otherwise an error will be reported.

Var str1 = teacher; // Error, no quotes, is considered js code, but JS does not have this syntaxCopy the code
  • String quotes are nested

JS can use single quotes to nest double quotes, or double quotes to nest single quotes (outer double inside single, outer single inside double)

If it’s a variable that’s defined by a single quote, if you want to put quotes inside the string, put them in double quotes

If it’s a variable that’s defined in double quotes, if you want to put quotes inside the string you should put them in single quotes

Var STR = '<h1 style="color:red"> </h1> document.write(STR);Copy the code
  • String escape

Escape characters all start with \

\n (newline) \t (TAB indent)

Get the length of the string

Grammar:

The variable name lengthCopy the code
Var len = str.length; var len = str.length; var len = str.length; console.log(len);Copy the code

String splicing

String concatenation uses + to concatenate

Multiple strings can be concatenated using +, which concatenates string + any type = new string after concatenation

To concatenate string and variable names, use only +

If one side of the + sign is string data then string concatenation will be performed

If you have numbers on both sides of the + sign, you’re doing an addition

// string concatenation console.log(' guan Gong '+' wu Da Dao '); Console. log(12 + 13); console.log(12 + 13); Console. log('12' + 13); console.log('12' + 13); / / '1213'Copy the code

+ sign summary formula: add values, join characters

String concatenation enhancement

Variables cannot be quoted because quoted variables become strings

Js string data we use string variables defined in single or double quotes. If a variable name is present in the string, the variable name will not be parsed.

Var age = 18 var STR = 'console.log(STR)'; var age = 18 var STR = 'console.log'; // Patrick is old this yearCopy the code

If you want to parse variables in strings, you use string concatenation.

Var age = 18 var str1 = 'console.log' (str1);Copy the code

Extended-template Strings (ES6)

Variable concatenation can be very error-prone, especially when single and double quotes occur together. Using template string syntax does not cause this problem,

Template strings declare strings using the key below the esc key in backquotes

Instead of concatenating template strings with plus signs, you can embed variables directly by writing them in ${}

Var age = 18 var STR = 'console.log(STR); ${age} console.log(STR);Copy the code

Extension – Template string case

Var STR = '<table> <tr> Name of the < th > < / th > < th > age < / th > < th > gender < / th > < th > height < / th > < / tr > < tr style = "text - align: center" > < td > ${username} < / td > < td > ${age} < / td > <td>${sex}</td> <td>${height}</td> </tr> </table> ` document.write(str)Copy the code

Style code:

 
table {
         width: 800px;
         margin: 0 auto;
         border: 1px solid red;
         border-collapse: collapse;
        }
​
        tr,
        td,
        th {
         border: 1px solid red;
 }
Copy the code

Show age case

Var age = prompt(' Please enter your age: ') Var res = 'this year ${age} is old' document.write(res)Copy the code

Boolean type

Boolean type, which represents true and false Boolean variables have only two values: true and false

True has a value of 1 and false has a value of 0.

Var flag = true; console.log(typeof flag);Copy the code

Undefined type

An undefined data type

How do I get undefined data types

  1. Declare a variable without assigning a value
  2. Declare a variable and assign the value of the variable to undefined
*/ var username console.log(typeof username); Var age = undefined console.log(typeof age); // undefined console.log(typeof age); // undefined console.log(typeof age); // undefinedCopy the code

null

Null data type

How do I get null data types

Assigns the value of a variable to null

Typeof () : null (object);

var v1 = null console.log(typeof v1); // Object // typeof is null.Copy the code

Reason: Why the Typeof operator returns “Object” for null values. This is actually a bug in the original implementation of JavaScript, a language design flaw left over from JavaScript history, and then adopted by ECMAScript. Null is now considered a placeholder for the object, thus explaining this contradiction, but technically it is still the original value. There was a proposed fix for ECMAScript, but it was brutally rejected and will never be fixed.

MDN details: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof

Summary of basic data types:

Number String Boolean(Boolean) Undefined Null

\