JavaScript (Basic Grammar)

Table of contents

Getting to know JavaScript

What is JavaScript

Development History

The relationship between JavaScript and HTML and CSS

JavaScript running process

The composition of JavaScript

Pre-knowledge

Written form of JavaScript

1. Inline

2. Embedded

3. External formula

note

input Output

input: prompt

Output: alert

Selection box: confirm

Output: console.log

Grammar overview

use of variables

basic usage

Understand dynamic typing

basic data type

number Number type

digital representation

special numeric value

string string type

basic rules

escape character

Find the length

string concatenation

boolean Boolean type

undefined undefined data type

null empty value type

operator

arithmetic operator

Assignment Operators & Compound Assignment Operators

Increment and decrement operators

comparison operator

Logical Operators

bit operation

shift operation

Conditional statements

if statement

ternary expression

switch

loop statement

while loop

continue

break

for loop

array

create array

get array element

Add new array element

delete an element in an array

function

grammatical format

About the number of parameters

function expression

scope

scope chain

object

basic concept

1. Use literals to create objects [commonly used]

2. Use new Object to create an object

3. Create an object using a constructor


Getting to know JavaScript


What is JavaScript

JavaScript ( JS for short )
  • is one of the most popular programming languages ​​in the world
  • is a scripting language that runs through an interpreter
  • It mainly runs on the client ( browser ) , and now it can also run on the server based on node.js

JavaScript was originally only used to complete simple form validation (verify data validity), but it became popular later accidentally.

Currently JavaScript has become a general-purpose programming language

Things JavaScript can do :
  • Web development ( more complex special effects and user interaction )
  • Web Game Development
  • Server development (node.js)
  • Desktop program development (Electron, VSCode is like this )
  • mobile app development

Development History

Brendan Eich, Father of JavaScript

In 1995, it took 10 days to complete the design of JS (due to the short design time, some details of the language were not carefully considered, which led to the chaos of the program written in Javascript for a long time later)

Originally at Netscape, named LiveScript,

It is generally believed that Netscape named LiveScript JavaScript because Java was the most popular programming language at the time, and the name "Java" helped spread the new language.

In fact, the syntax style between Java and JavaScript is very different.

The relationship between JavaScript and HTML and CSS

  • HTML: The Structure of a Web Page ( Bone )
  • CSS: Web page performance ( skin )
  • JavaScript: Behavior of Web Pages ( Soul )

JavaScript running process

  • The written code is saved in the file , that is, stored on the hard disk ( external storage ).
  • Double-click the .html file browser ( application ) to read the file and load the content of the file into memory ( data flow direction : hard disk => memory )
  • The browser will parse the code written by the user and translate the code into binary instructions that can be recognized by the computer ( the work of the interpreter )
  • The obtained binary instructions will be loaded and executed by the CPU ( data flow direction : memory => CPU)

The browser is divided into rendering engine + JS engine .
  • Rendering engine : parse html + CSS, commonly known as " kernel "
  • JS engine : that is, the JS interpreter . Typical is the built-in V8 in Chrome

The composition of JavaScript

  • ECMAScript ( ES for short ): JavaScript syntax
  • DOM: Page Document Object Model , which operates on elements in the page
  • BOM: browser object model , to operate on the browser window

With JS syntax alone, only some basic logic processes can be written.

But in order to complete more complex tasks and complete the interaction with browsers and pages, DOM API and BOM API are needed for a long time.

Key Concepts: ECMAScript

This is a set of "standards", no matter what kind of JS engine it is, it must comply with this standard.

Pre-knowledge


<script>
    alert("你好!");
</script>
  • JavaScript code can be embedded in HTML script tags.

Written form of JavaScript

1. Inline

Embed directly inside the html element
<input type="button" value="点我一下" onclick="alert('haha')">
Notice
  • String constants in JS can be expressed in single quotes or double quotes .
  • Double quotes are recommended in HTML , and single quotes are recommended in JS .

2. Embedded

write in the script tag
<script>
    alert("haha");
</script>

3. External formula

Write to a separate .js file
<script src="hello.js"></script>
alert("hehe");

In this case, the code cannot be written in the middle of the script tag. It must be empty (the code will not be executed if written).

note

Single-line comments // [recommended]

Multi-line comment /* */

  • Use ctrl + / to toggle comments .
  • Multiline comments cannot be nested .

input Output

input : prompt

pop up an input box
// 弹出一个输入框
prompt("请输入您的姓名:");

Output : alert

Pop up a warning dialog box , output the result
// 弹出一个输出框
alert("hello");
  • + indicates string concatenation , that is, two strings are connected end to end to form a string .
  • \n means newline

Selection box: confirm

A selection dialog pops up, confirm or cancel

// 弹出选择框
confirm("确认删除吗?");

Output : console.log

Print a log on the console ( for programmers to see )
// 向控制台输出日志
console.log("这是一条日志");
  • Enter "log" directly in VSCode and press the tab key to quickly enter console.log

You need to open the browser's developer tools (F12) => Console tab to see the results.

Key Concepts : Logging
Logs are an important means for programmers to debug programs
Important concepts : .
console is an " object " in js
.Indicates to take a certain property or method in the object . It can be intuitively understood as " of "
console.log can be understood as : use the "log method " of the " console " object .

Grammar overview


Although some design concepts of JavaScript are far from Java, there are still some similarities at the basic grammar level. With the foundation of Java, it is easy to understand some basic grammar of JavaScript.

use of variables

basic usage

Create variables (variable definition/variable declaration/variable initialization)

var name = 'zhangsan';
var age = 20;
  • var is a keyword in JS , indicating that this is a variable .
  • = means " assignment " in JS , which is equivalent to putting data into a memory box . A space is recommended on both sides of =
  • Each statement ends with a ; at the end . It can be omitted in JS ; but it is recommended to add it .
  • Note that the ; here is an English semicolon . All punctuation in JS is English punctuation .
  • If the initialized value is a string , it must be enclosed in single or double quotes .
  • If the initialized value is a number , then it can be assigned directly .
use variables
console.log(age); // 读取变量内容
age = 30;         // 修改变量内容

Understand dynamic typing

1) The variable type of JS is determined during the running of the program ( the type will be determined only when the = statement is run )
var a = 10;     // 数字
var b = "hehe"; // 字符串
2) As the program runs , the type of the variable may change .
var a = 10;    // 数字
a = "hehe";    // 字符串

basic data type

Several types built into JS
  • number: number . Integers and decimals are not distinguished .
  • boolean: true true , false false .
  • string: string type .
  • undefined: Only the unique value undefined. Indicates an undefined value .
  • null: Only the unique value null. Indicates a null value .

numberNumber type

JS does not distinguish between integers and floating-point numbers, and uses "number types" to represent them uniformly.

digital representation

var a = 07;      // 八进制整数, 以 0 开头
var b = 0xa;     // 十六进制整数, 以 0x 开头
var c = 0b10;    // 二进制整数, 以 0b 开头
Note :
  • One octal digit corresponds to three binary digits
  • One hexadecimal digit corresponds to four binary digits . ( Two hexadecimal digits are one byte )

special numeric value

  • Infinity: Infinity , greater than any number . It means that the number has exceeded the range that JS can represent .
  • -Infinity: Negative infinity , less than any number . It means that the number has exceeded the range that JS can express .
  • NaN: Indicates that the current result is not a number .
var max = Number.MAX_VALUE;
// 得到 Infinity
console.log(max * 2);
// 得到 -Infinity
console.log(-max * 2);
// 得到 NaN
console.log('hehe' - 10);
Note :
  1. Negative infinity and infinitesimal are not the same thing . Infinity small means infinite approach to 0, the value is 1 / Infinity
  2. The result of 'hehe' + 10 is not NaN, but 'hehe10', which will implicitly convert the number into a string , and then concatenate the string .
  3. You can use the isNaN function to determine whether it is a non-number .

string string type

basic rules

String literals need to be enclosed in quotes, either single quotes or double quotes.

If the string already contains quotation marks, escape characters need to be used.

escape character

Some characters are inconvenient to input directly , so they have to be expressed in some special ways .
  • \n
  • \\
  • \'
  • \"
  • \t

Find the length

Use the length property of String

string concatenation

  • Use + to splice
  • Numbers and strings can also be concatenated

boolean Boolean type

Indicates "true" and "false"

  • When Boolean participates in operations, it is treated as 1 and 0 .

undefined undefined data type

If a variable has not been initialized , the result is undefined , which is of type undefined
var a;
console.log(a)
Add undefined and string , and the result is string concatenation
console.log(a + "10");  // undefined10
Undefined is added to a number , and the result is NaN
console.log(a + 10);

null empty value type

null indicates that the current variable is a " null value ".

var b = null;
console.log(b + 10);    // 10
console.log(b + "10");  // null10
Note :
  • Both null and undefined indicate illegal values , but the emphasis is different .
  • Null means that the current value is empty . ( equivalent to having an empty box )
  • undefined means that the current variable is undefined . ( equivalent to not even having a box )

operator

Operators in JavaScript are basically the same as in Java

arithmetic operator

  • +
  • -
  • *
  • /
  • %

Assignment Operators & Compound Assignment Operators

  • =
  • +=
  • -=
  • *=
  • /=
  • %=

Increment and decrement operators

  • ++: increment by 1
  • --: decrement by 1

comparison operator

  • <
  • >
  • <=
  • >=
  • == compares equal ( will perform implicit type conversion )
  • !=
  • === compares equal ( no implicit type conversion )
  • !==

Logical Operators

Used to evaluate multiple boolean expressions .
  • && and : one false is false
  • || or : one true is true
  • ! Non

bit operation

  • & bitwise AND
  • | bitwise or
  • ~ bitwise negation
  • ^ bitwise XOR

shift operation

  • << shift left
  • >> signed right shift ( arithmetic right shift )
  • >>> Unsigned right shift ( logical right shift )

Conditional statements

if statement

basic grammar format
If the conditional expression is true, execute the code in { } of if
// 形式1
if (条件) {
    语句
}
// 形式2
if (条件) {
    语句1
} else {
    语句2
}
// 形式3
if (条件1) {
    语句1
} else if (条件2) {
    语句2   
} else if .... {
    语句...
} else {
    语句N
}

ternary expression

It is a simplified way of writing if else .
条件 ? 表达式1 : 表达式2
If the condition is true , return the value of expression1 . If the condition is false , return the value of expression2

switch

More suitable for multi-branch scenarios
switch (表达式) {
    case 值1:
        语句1;
        break;
    case 值2:
        语句2:
        break;
    default:
        语句N;
}

loop statement

repeat some statements

while loop

while (条件) {
    循环体;
}
Execution process :
  • conditional statement
  • If the condition is true, execute the loop body code .
  • If the condition is false, the loop ends directly

continue

end this cycle

break

end the whole loop

for loop

for (表达式1; 表达式2; 表达式3) {
 循环体
}
  • Expression 1: Used to initialize the loop variable .
  • Expression 2: loop condition
  • Expression 3: update loop variable
Execution process :
  • Execute expression 1 first, initialize the loop variable
  • Execute expression 2 again to determine the loop condition
  • If the condition is false, end the loop
  • If the condition is true, execute the loop body code .
  • Execute expression 3 to update the loop variable

array

create array

Created using the new keyword
// Array 的 A 要大写
var arr = new Array();
Use literal method to create [ commonly used ]
var arr = [];
var arr2 = [1, 2, 'haha', false]; // 数组中保存的内容称为 "元素"
  • JS arrays do not require elements to be of the same type

get array element

  • Access array elements using subscripts ( starting from 0 )
  • If the subscript is out of range to read the element , the result is undefined

Add new array element

1. Added by modifying length
It is equivalent to adding an element at the end . The default value of the newly added element is undefined
2. Add by subscript
If the subscript exceeds the range of the assigned element , a new element will be inserted at the specified position
3. Use push to add elements
var arr = [9, 5, 2, 7, 3, 6, 8];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
   newArr.push(arr[i]);
}

delete an element in an array

Remove elements using the splice method
var arr = [9, 5, 2, 7];
// 第一个参数表示从下表为 2 的位置开始删除. 第二个参数表示要删除的元素个数是 1 个
arr.splice(2, 1);
console.log(arr);
// 结果
[9, 5, 7]

function

grammatical format

// 创建函数/函数声明/函数定义
function 函数名(形参列表) {
    函数体
    return 返回值;
}
// 函数调用
函数名(实参列表)           // 不考虑返回值
返回值 = 函数名(实参列表)   // 考虑返回值
  • The function definition does not execute the content of the function body , it must be called before it will be executed . It will be executed several times after being called several times .
  • When the function is called, it enters the internal execution of the function , and when the function ends, it returns to the calling location and continues to execute . It can be observed with the help of a debugger .
  • There is no requirement for the order of function definition and calling . ( This is different from variables , variables must be defined before use )

About the number of parameters

The number of actual parameters and formal parameters may not match. However, actual development generally requires that the number of formal parameters and actual parameters should match

  • 1) If the number of actual parameters is more than the number of formal parameters , the extra parameters will not participate in the function operation
  • 2) If the number of actual parameters is less than the number of formal parameters , the value of the extra formal parameters at this time is undefined

function expression

Another way to define a function

var add = function() {
 var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
   }
    return sum;
}
console.log(add(10, 20));            // 30
console.log(add(1, 2, 3, 4));        // 10
console.log(typeof add);             // function
A wording like function() { } defines an anonymous function , and then represents the anonymous function with a variable .

scope

The valid scope of an identifier name in the code.

Before the ES6 standard, the scope was mainly divided into two

  • Global scope : It takes effect in the entire script tag , or in a separate js file .
  • Local scope / function scope : takes effect inside the function .

scope chain

Background :
  • Functions can be defined inside functions
  • Inner functions can access local variables of outer functions .

object

basic concept

object refers to a specific thing

In JS, strings, numbers, arrays, and functions are all objects.

Each object contains several properties and methods .
  • Attributes : characteristics of things .
  • Method : the behavior of things .

The concept of JavaScript objects and Java objects is basically the same . It is just that the specific syntax table entries are quite different .

1. Use literals to create objects [ commonly used ]

Create objects using { }
  • Create objects using { }
  • Properties and methods are organized as key-value pairs .
  • Used between key-value pairs , split . After the last attribute , optional
  • Use : split between keys and values .
  • The value of the method is an anonymous function

2. Use new Object to create objects

var student = new Object(); // 和创建数组类似
student.name = "蔡徐坤";
student.height = 175;
student['weight'] = 170;
student.sayHello = function () {
    console.log("hello");
}

3. Create objects using constructors

The previous method of creating an object can only create one object. Using the constructor can easily create multiple objects

function 构造函数名(形参) {
    this.属性 = 值;
    this.方法 = function...
}
    
var obj = new 构造函数名(实参);
Note :
  • Use the this keyword inside the constructor to denote the object currently being constructed .
  • The first letter of the function name of the constructor is usually capitalized .
  • The function name of the constructor can be a noun .
  • Constructors don't need to return
  • The new keyword must be used when creating an object .

Guess you like

Origin blog.csdn.net/m0_59952648/article/details/131554453