Grammar JS Basics

1. First knowledge of JavaScript

1.1 Outlook

 CSS preprocessor
CSS preprocessor defines a new language. Its basic idea is to use a special programming language to add some
programming features to CSS, use CSS as the target to generate files, and then developers only need to Use this language for CSS coding. Converting it
into easy-to-understand words means "use a special programming language to design the Web page style, and then convert it into a normal
CSS file through a compiler for project use."
What are the commonly used CSS preprocessors

  • SASS: Based on Ruby, it is processed through the server and has powerful functions. High analysis efficiency. You need to learn the Ruby language, which is more difficult than LESS.
  • LESS: Based on NodeJS, processed by the client, easy to use. The function is simpler than SASS, and the parsing efficiency is lower than
  • SASS, but it is enough in actual development, so we recommend using LESS if needed.

1.2 Introduction to JavaScript

JavaScript is an object-based and event-driven client-side scripting language with relative security. It is widely used in various client web programs, especially in HTML development. It can add dynamic functions to HTML web pages, respond to various operations of users, and realize special effects such as welcome information, digital calendar, marquee, and display of browser stay time. Improve the viewability of web pages.

1.3 JavaScript framework

  • jQuery: a well-known JavaScript framework, the advantage is that it simplifies the DOM operation, and the disadvantage is that the DOM operation is too frequent, which affects the performance of the front-end; it is only used in the eyes of the front-end for compatibility with IE6, 7, and 8; 
  • Angiar: The front-end framework acquired by Google was developed by a group of Java programmers. It is characterized by moving the back-end MVC model to the front-end and adding the concept of modular development. It cooperates with Microsoft and uses TypeScript syntax to develop; it is friendly to back-end programmers. It is not very friendly to front-end programmers; the biggest disadvantage is that the version iteration is unreasonable (for example: 1st generation -> 2nd generation, except for the name, it is basically two things; Angular6 has been launched by the time of publishing the blog) 
  • React: Produced by Facebook, a high-performance JS front-end framework; the feature is that a new concept [virtual DOM] is proposed to reduce real DOM operations, simulate DOM operations in memory, and effectively improve front-end rendering efficiency; the disadvantage is that it is complicated to use , because it is necessary to learn an additional [JSX] language; 
  • Vue: A progressive JavaScript framework. The so-called progressive means to gradually realize new features, such as the realization of new features such as modular development, routing, and status management. It is characterized by combining the advantages of Angular (modularization) and React (virtual DOM); 
  • Axios: front-end communication framework; because the boundary of Vue is very clear, it is for processing DOM, so it does not have communication capabilities, and an additional communication framework is needed to interact with the server; of course, you can also directly choose to use the AJAX communication function provided by jQuery ;

1.4 UI framework

 Supplement: WeChat applet WeUI

1.5 JavaScript usage

  • JavaScript gets all the power to create dynamic HTML:
  • JavaScript can change all HTML elements in the page
  • JavaScript can change all HTML attributes in the page
  • JavaScript can change all CSS styles in the page
  • JavaScript can remove existing HTML elements and attributes
  • JavaScript can add new HTML elements and attributes
  • JavaScript can react to all existing HTML events in the page
  • JavaScript can create new HTML events in the page

1.6 Quick Start

1.6.1 Getting Started with Formats

 Putting the script at the bottom of the <body> element can improve the display speed, because script compilation will slow down the display, and the JS code is recommended to be placed at the bottom of the body

External script references can be placed in <head> or <body>

1.6.2 Grammar Primer

1.7 Browser Console Use

//console.log(score) prints variables on the browser's console! 

1.8 Summary

  • Semicolons separate JavaScript statements, adding a semicolon after each executable statement
  • Comments: Single-line comments start with //; multi-line comments start with /* and end with */
  • JavaScript identifiers are case sensitive

2. Introduction to JavaScript

2.1 Composition

A complete JavaScript implementation consists of the following three parts:

  • ECMAScript: The Core Standard.
  • DOM: Document Object Model.
  • BOM: Browser Object Model.

ECMAScript is the core standard of JavaScript, which describes the syntax and basic objects of the language.

DOM refers to Document Object Model (Document Object Model), which is the application programming interface of HTML. DOM regards the entire HTML page as a structural document composed of various node levels.

BOM refers to the Browser Object Model (browser object model), which can access and operate the browser window
.

2.2 JavaScript usage

  • Internal JavaScript
  • External JavaScript

Internal JavaScript

 2.3 Variables

  • let, declares a variable with scope
  • const, declares a constant with scope
  • Arrow Functions, arrow functions suitable for shorthand anonymous functions

2.3.1 Declaration of variables

var a;
const a=1; //必须赋值
let a;//块内元素

JavaScript is a weakly typed scripting language. Whether it is a number, text or other content, it is declared with the keyword var plus the variable name

Variable declaration is not necessary, it can be directly used without keyword var declaration.

2.3.2 Variable assignment

Common variable assignments are numeric or textual. When the variable assignment content is text, you need to use quotation marks
(single quotation marks and double quotation marks are acceptable) to enclose the content; when assigning a value to a variable, do not add quotation marks to the content,
otherwise it will be treated as a string.

2.3.3 Naming convention

2.3.4 JavaScript keywords and reserved words

2.3.5 Strict detection mode

2.3.6 Variable scope

global variable 

 local scope (let)

2.3.7 Method definition and call

define method

apply keyword

 2.4 Basic data types

JavaScript has five primitive types: Number (number), Boolean (Boolean value), String (string), Null (empty value) and Undefined (undefined).

2.4.1Number type

Use the Number type to represent numbers in JavaScript, and the numbers can be
integers within 32 bits or floating point numbers within 64 bits

  • Octal numbers need to start with the number 0
  • Hexadecimal numbers need to start with the number 0 and the letter x
  • Floating-point numbers can use the toFixed() method to specify how many digits to keep after the decimal point (comply with rounding).
    123 //整数
    .15 //浮点数
    1.123e3 //科学计数
    -99 //负数
  • special value
//正确转换为Number类型时返回真(true),其他情况返回假(false)
isNaN(变量名称)

2.4.2String type

Common methods:

  1. Get the string length msg.length
  2. Get a single character in a string msg.charAt(1) code number msg.charCodeAt(1) 
  3. Connection string msg.concat (to be connected string)
  4. Find if a string exists
  5. Find and replace string msg.match(regex) msg.search(regex) msg.replace(regex, replace text)
  6. Get the string fragment slice (start, end) to remove the specified string, subtring (start, end) to get
  7. String case conversion toLowerCase(), toUpperCase()
  8. Escape characters are the same as C++

2.4.3 Boolean type

Boolean ( boolean ) is used for conditional judgment in many programming languages, and its value has only
two types: true (true) or false (false).

2.4.4 Undefined type

All output values ​​of type undefined are undefined. When the variable to be output has never been declared, or the keyword
var is used to declare but never assigned, the word undefined will be displayed.

2.4.5 Null type

2.5 Common operators

2.5.1 Assignment Operators

2.5.2 Arithmetic operators

Try to avoid using floating-point numbers for operations, there are precision problems

2.5.3 Logical operators

There are three types of logical operators: NOT (logical not), AND (logical and), and OR (logical or).

2.5.4 Relational Operators

In JavaScript, there are four types of relational operators: greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). It is used to compare the size of two values, and the return value must be a Boolean value (true or false).

2.5.5 Equality Operators

2.5.6 Conditional operator (ternary operator) 

2.5.7 Two common functions

2.6 Statement

2.6.1 Conditional Statements

  • if statement
  • switch statement

Same as C++ syntax

2.6.2 Loop statement

JavaScript supports different types of loops:

  • for - iterate over a block of code multiple times
  • for/in - loop over object properties
  • while - loop a block of code while the specified condition is true
  • do/while - Loop a block of code while a specified condition is true

2.7 Functions

2.7.1 Defining functions

Definition one

Definition method two

 Parameter problem: javaSqript can pass any number of parameters, or no parameters-

abnormal judgment

<script>
        var abs = function (x){
            if (typeof x != 'number'){
                throw 'not a number';
            }
            if(x > 0){
                return x;
            }
            else {
                return -x;
            }
        }
    </script>

arguments keyword

arguments is a free keyword given by JS; it means that all the parameters passed in are an array!

 <script>
        var abs = function (x){
            console.log("x=>"+x);
            for (let i = 0; i < arguments.length; i++) {
                console.log(arguments[i])
            }
            if(x > 0){
                return x;
            }
            else {
                return -x;
            }
        }
    </script>

rest keyword

The new feature introduced by ES6, get all the parameters except the parameters already defined~ ...

<script>
        var abs = function (x,...rest){
            console.log("x=>"+x);
            console.log(rest)
            if(x > 0){
                return x;
            }
            else {
                return -x;
            }
        }
    </script>

2.7.2 Basic functions

Compared with Java, JavaScript functions are simpler and do not need to declare the return value type.
If the JavaScript function has a return value, directly use the return keyword in the code block inside the curly braces followed by the value to be returned.

 2.7.3 Arrow functions

 2.8 JavaScript Object Types

  • local object
  • built-in object
  • host object

●Native object (native object) is a reference type defined by ECMAScript;
●Built-in object (built-in object) refers to an object that can be used directly without instantiation, and is actually a special local object;
●Host object (host object) refers to What is the user's machine environment, including DOM and BOM.

local object

2.8.1 Arrays

Java values ​​must be objects of the same type~, this is not required in JS!
var arr = [1,2,3,4,5, 'he11o' ,nu11,true]
The Array object also contains a length attribute, which can be used for Get the length of the current array, that is, the number of elements in the array. If the current array contains no elements, the length value is 0

2.8.2 Date Data

Use the Date object in JavaScript to handle time and date related content. There are four initialization methods

common method 

2.8.3 Regular expressions

grammatical format

 common method

2.8.4Map and Set collections (ES6 new features)

Map

<script>
        'use strict';
        let map = new Map([['BO', 90], ['tom', 100]]);
        let name = map.get('BO');
        map.set('admin',100);
        map.delete('admin');
        console.log(name);
    </script>

Set

  <script>
        'use strict';
        let set = new Set([3,1,1,1]);
        set.add(2);
        set.delete(1);
        console.log(set.has(3));
    </script>

2.8.5iterator

2.8.6 Objects

Objects are also variables. But the object contains a lot of value value name: value pair way to write (name and value separated by colon)

method to get the object

built-in object

  • Gobal object
  • Math object

host object

2.8. 7DOM events

JavaScript can also execute code when the state of the HTML page changes. This state change is called a DOM event (Event).

Defined:

  • HTML elements as objects
  • Attributes of all HTML elements
  • Methods to access all HTML elements
  • Events for all HTML elements

In other words: HTML DOM is a standard on how to get, change, add or remove HTML elements.

The W3C DOM standard is divided into 3 distinct parts:

  • Core DOM - the standard model for all document types
  • XML DOM - standard model for XML documents
  • HTML DOM - the standard model for HTML documents

When a browser parses an HTML webpage, it creates an HTML DOM model object, invokes DOM methods by executing JavaScript code, and manipulates the content/attributes/events of HTML elements, thereby realizing interaction with the HTML page

2.8.8 Manipulating BOM objects

The Browser Object Model (Browser Object Model, BOM) enables JavaScript to interact with the browser.

common objects

  • window: browser window object, its members include all global variables, functions and objects
  • screen : Screen object, usually used to obtain the width and height of the user's available screen.
  • location : A location object, used to obtain the URL address of the current page, and redirect the browser to a new specified page.
  • history : History object, which contains the browsing history of the browser.
  • navigator: browser object, usually used to obtain information about the user's browser.

window object

In JavaScript, the window object represents the browser window, and currently all browsers support this object. All global variables, functions, and objects in JavaScript automatically become the contents of the window object.


For example, the global method isNaN() for judging whether a variable is a number is the method of the window object, and the full writing method is window.isNaN(). Normally, the window prefix can be omitted.

 common method

 navigator object

In JavaScript, the window.navigator object can be used to obtain a series of information about the user's browser, such as the name and version number of the browser. The object can usually omit the window prefix when using it, abbreviated as navigator

Most of the time, we will not use the navigator object, because it will be artificially modified! It is not recommended to use these properties to judge and write code

screen object

The window.screen object can be used in JavaScript to get the available width and height of the screen. When using this object, the window prefix can usually be omitted, and it is abbreviated as screen.

 location object

 document object

history object 

 Represents browser history

history.back()
history.forward()

2.8.9 Manipulating DOM objects

The browser web page is a Dom tree structure!

  • UPDATE: Updating Dom Nodes
  • Traverse dom nodes: get Dom nodes
  • Delete: Delete a Dom node
  • add: add a new node

To operate a Dom node, you must first obtain the Dom node

Find HTML elements

  • Lookup by HTML element's id name;
  • Find by HTML element's tag name:
  • Lookup by HTML element's class name

 update node

Modify HTML text content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="id1">
    123
</div>
<script>
  var id1 = document.getElementById('id1');
  //动态创建文本内容
  var date = new Date();
  document.write("当前时间为"+date.toLocaleDateString());
  //修改文本的值
  id1.innerText="456";
  //修改解析HTML文本标签
  id1.innerHTML='<strong>789</strong>';
</script>
</body>
</html>

Modify HTML element attributes

Modify the CSS style of HTML

 Delete DOM node

 Steps to delete a node: Get the parent node first, then delete yourself through the parent node
Note: When deleting multiple nodes, the children change at any time, so be sure to pay attention when deleting nodes!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="father">
    <h1>标题</h1>
    <p id="p1">p1</p>
    <p id="p2">p2</p>
</div>
<script>
  var self = document.getElementById('p1');
  var father = p1.parentElement;
  father.removeChild(self);
</script>
</body>
</html>

insert node 1 create

 insert node 2

 2.9 Type Conversion

 2.9.1 Convert to String

//布尔值类型(Boolean)和数字类型(Number)这两种基本数据类型均可使用toString()方法
//把值转换为字符串形式
var x = true;
var result = x.toString(); //返回"true"
//toString()不带参数直接使用,此时无论是整数、小数或者科学计数法表示的内容,都会显示为十进制的数值
var x1 = 99;
var x2 = 99.90;
var x3 = 1.25e8;
 
var result1 = x1.toString(); //返回值为"99"
var result2 = x2.toString(); //返回值为"99.9"
var result3 = x3.toString(); //返回值为"125000000"
var x = 10;
var result1 = x.toString(2); //声明将原始数据转换成二进制数,返回值为"1010"
var result2 = x.toString(8); //声明将原始数据转换成八进制数,返回值为"12"
var result3 = x.toString(16); //声明将原始数据转换成十六进制数,返回值为"A"

var x = null;
var result1 = String(x); //返回值为字符串"null"
var result2 = x.toString(); //发生错误,无返回值

2.9.2 Conversion to numbers

var x = "123hello";
var result = parseInt(x); //返回值是123,因为h不是有效数字,则停止检查

var x = "hello";
var result = parseInt(x); //返回值是NaN,因为第一个字符h就不是有效数字,直接停止检查

var x = "3.14";
var result = parseInt(x); //返回值是3,因为小数点不是有效数字,则停止检查

var x = "10";
var result1 = parseInt(x, 2); //表示原始数据为二进制,返回值为2
var result2 = parseInt(x, 8); //表示原始数据为八进制,返回值为8
var result3 = parseInt(x, 10); //表示原始数据为十进制,返回值为10
var result4 = parseInt(x, 16); //表示原始数据为十六进制,返回值为16

var x = "010";
var result1 = parseInt(x); //表示原始数据为八进制,返回值为8
var result2 = parseInt(x, 10); //表示原始数据为十进制,返回值为10
var result3 = parseInt(x, 8); //表示原始数据为八进制,返回值为8
var x = "hello3.14";
var result = parseFloat(x); //返回值是NaN,因为第一个字符h就不是有效数字,则停止检查

var x = "3.14hello";
var result = parseFloat(x); //返回值是3.14,因为h不是有效数字,则停止检查

var x = "3.14.15.926";
var result = parseFloat(x); //返回值是3.14,因为第二个小数点不是有效数字,则停止检查

var x = "010";
var result1 = parseInt(x); //默认为是八进制数,返回值为8
var result2 = parseFloat(x); //默认为是十进制数,返回值为10

var x = "A";
var result1 = parseInt(x, 16); //parseInt()允许十六进制数,返回值为10
var result2 = parseFloat(x); //parseFloat()不允许十六进制数,返回值为NaN

2.9.3 Mandatory type conversion

Boolean() function

Number function

String function

 3. High-level JavaScript

3.1 JavaScript output

JavaScript doesn't have any print or output functions

JavaScript can output data in different ways

  • Use window.alert() to pop up an alert box
  • Use the document.write() method to write the content to the HTML document
  • Write to HTML elements using innerHTML
  • Use console.log() to write to the browser's console

Use window.alert()

Use the document.write() method

 Write using innerHTML

To access an HTML element from JavaScript, use the document.getElementById(id) method; use innerHTML to get or insert element content;

 Use console.log()

3.2JSON object/BSON

JSON: JavaScript Object Notation. JSON is a lightweight data exchange format for storing and transmitting data

The JSON format is syntactically identical to creating JavaScript object code

Json, which describes JS objects through text, is convenient for converting JS objects to pass operations, attributes are stored in key-value pairs, braces, semicolons, double quotes, commas, square brackets (arrays), methods, etc.

Format:
●All objects use {}
●Arrays all use []
●All key-value pairs use key:value

The backend fetches the data from the database, converts the data into Java objects, converts the Java objects into json strings, passes the json strings to the front end through the network, converts the json strings into JavaScript objects, and JavaScript converts the data in the JavaScript objects render to the page

3.3 Object-Oriented Programming

3.3.1 Prototypal inheritance

<script>
        'use strict';
        let Student = {
            name:"yanyu",
            age:20,
            run:function (){
                console.log(this.name+"run")
            }
        };
        let BO = {
            name: "BO"
        };
        BO.__proto__ = Student;
    </script>

3.3.2 class inheritance

define a class

inherit

prototype chain 

3.4 Event Overview

The event handler is the action to be taken when the event occurs. The onload attribute is what we call an event handler, also known as an event attribute.

 form event

select event

 keyboard events

window event

3.5 DOM events

JavaScript can also execute code when the state of the page changes, which is called a DOM event (event).

3.6 Operation form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
</head>
<body>
<form action="https://www.baidu.com/" method="post" onsubmit="return aaa()">
    <p>
    <span>用户名:</span><input type="text" id ="username" name="username">
    </p>
    <p>
        <span>密码:</span><input type="password" id="input-password">
    </p>
    <input type="hidden" id="md5-password" name="password">
    <button type="submit">提交</button>
</form>
<script>
  function aaa(){
      var uname = document.getElementById('username');
      var pwd = document.getElementById('input-password');
      var md5pwd = document.getElementById('md5-password');
      md5pwd.value=md5(pwd.value);
      return true;
  }
</script>
</body>
</html>

4. Key Grammatical Supplement

4.1 Add/Delete New Attributes

4.2 Convert object to array

4.3 Accessors

 4.4 Object Constructor

 4.5 Object Prototype

 4.6 JAVASCRIPT class

4.7 Callbacks

 4.8 Asynchronous

A function that runs in parallel with other functions is called asynchronous

4.8.1 Waiting for timeout

 4.8.2 Wait interval

 4.9Promise

4.10 asynchronism asynchronous

 

 4.11Call() method

 

 4.12 apply () method

4.13 Nested functions

 4.14 Self-invoking functions

4.15 Closures

 4.16 Template Strings

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_62377885/article/details/130998981