Table of contents
The relationship between JavaScript and HTML and CSS
Assignment Operators & Compound Assignment Operators
Increment and decrement operators
About the number of parameters
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
- 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
- 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)
- 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
<input type="button" value="点我一下" onclick="alert('haha')">
- 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
<script>
alert("haha");
</script>
3. External formula
<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
// 弹出一个输入框
prompt("请输入您的姓名:");
Output : alert
// 弹出一个输出框
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
// 向控制台输出日志
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.
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 .
console.log(age); // 读取变量内容
age = 30; // 修改变量内容
Understand dynamic typing
var a = 10; // 数字
var b = "hehe"; // 字符串
var a = 10; // 数字
a = "hehe"; // 字符串
basic data type
- 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 开头
- 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);
- Negative infinity and infinitesimal are not the same thing . Infinity small means infinite approach to 0, the value is 1 / Infinity
- The result of 'hehe' + 10 is not NaN, but 'hehe10', which will implicitly convert the number into a string , and then concatenate the string .
- 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
- \n
- \\
- \'
- \"
- \t
Find the length
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
var a;
console.log(a)
console.log(a + "10"); // undefined10
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
- 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
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
- && 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
// 形式1
if (条件) {
语句
}
// 形式2
if (条件) {
语句1
} else {
语句2
}
// 形式3
if (条件1) {
语句1
} else if (条件2) {
语句2
} else if .... {
语句...
} else {
语句N
}
ternary expression
条件 ? 表达式1 : 表达式2
switch
switch (表达式) {
case 值1:
语句1;
break;
case 值2:
语句2:
break;
default:
语句N;
}
loop statement
while loop
while (条件) {
循环体;
}
- conditional statement
- If the condition is true, execute the loop body code .
- If the condition is false, the loop ends directly
continue
break
for loop
for (表达式1; 表达式2; 表达式3) {
循环体
}
- Expression 1: Used to initialize the loop variable .
- Expression 2: loop condition
- Expression 3: update loop variable
- 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
// Array 的 A 要大写
var arr = new Array();
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
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
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
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
- 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.
- 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 { }
- 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 构造函数名(实参);
- 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 .