Notes on Web Learning Route JS: Introduction

1.js is an interpretive programming language running on the client

2. Functions of JS:

Some logical implementations used to complete front-end and back-end interaction and increase user experience.

3. A web page is composed of three parts: structure (HTML/HTML5), presentation (CSS/CSS3) and behavior (javascript)

4. The core of front-end development is javascript

5. Composition of JavaScript

  1. ECMAScript (standard: ECMA-262): basic language part (basic, object-oriented, etc.)
  2. DOM (standard: W3C): node operation
  3. BOM (no standard): browser operation

6. Features of JS

1. Looseness
js variables do not have an explicit type, which is also called weakly typed language (allowing a piece of memory to be regarded as multiple types)
2. Object attributes
The properties of an object can also be mapped to arbitrary data
3. Succession mechanisms
js is based on prototype inheritance

7. Use javascript

use js A dialog box pops up
	<Script>
	 	alert("hello world!");
	 </Script>
<script type="text/javascript" defer="defer">

<--!defer =" defer" Indicates loading DOM Load after completion js code
 however es6 You don't need to write it in the future. It's added by default-->

be careful:

The script tag can be written anywhere in the web page code, because js is executed synchronously, but in order to avoid js blocking, it is best to write it after the body.

alert('</sc'+'ript'); <--!eject /script The text should be written like this-->

7.1 three ways of using JS

1. Use the script tag to write directly in the script tag
2. Write it in the href of a tag (poor performance, not recommended)

<a href="javascript:var a=10,b=20;alert('The result is:'+(a+b))"> Label 1 </a>
<a href="javascript:close();">&times;</a>  Close the current page. See the specific example vscode
<!-- Close current page -->
    <a href="javascript:close();">&times;</a>
    <!-- Prevent page refresh -->
    <a href="javascript:void(1);">Prevent page refresh</a>
    <a href="javascript:alert('i love you')">Pop up warning box</a>

3. Use external script to load js

	<script scr="01_test.js" type="text/javascript" async="async"> </script>

async: execute scripts asynchronously, that is, when executing DOM, another line executes js code at the same time, but it is only used for external scripts

8. Identifier

1. Grammar
Case sensitive
Everything in ECMAScript, including variables, function names, and operators, is case sensitive. For example, Book and Book represent two variables.

2. Identifier:
The so-called identifier refers to the name of a variable, function, attribute, or the parameter of a function. The identifier can be one or more characters combined by the following format rules:
1) The first character must be a letter or underscore_ Or a dollar sign$
2) Other characters can be letters, underscores, dollar symbols, or numbers.
3) Keywords, reserved words, true, false, and nll cannot be used as identifiers.

Comments: ECMAScript uses c-style comments, including single line comments and block level comments.

keyword:
break , else, new, var,case,finally,return , void ,catch, for,switch,while
continue,function,this,with,default,if,throw,delete,in,try,do,instanceof,typeof, etc


Note: js is strictly case sensitive anywhere.

9. Notes

1) Single line note
//Note content
It is generally used to describe a single line code
2) Multiline comment
/*
...
...
*/
Also called block annotation. Generally, the following codes are described as a whole, and there may be many descriptions.

For example:

/*
*Requirements: write a program, input the content with the keyboard, and then output it in the browser
*1)Introduce prompt() method
*2)Output to browser
**/
<script type="text/javascript" charset="utf-8" ansync="ansync" defer="defer" >
	var user_input = prompt("Please enter a message!");  /
	document.write("The message you entered is:"+user_input);
</script>
explain:

Comments will not be executed. You should get used to writing comments in the project to facilitate later project maintenance.

10. Constant

Constant is also called direct quantity or literal quantity. It gives specific data directly in the program.
Constants cannot be changed.
For example: 100, true, "abc", null, undefined, etc

definition:
1) Define variables only
var x ;
var a, b, c;
2) Define variables and assign values
var x1 = true;
var y1 = 100, y2 = null;

explain:

​ 1. When defining variables, it is not necessary to give the type of data (the characteristic of loose language)

<script>
    var x = 100;
    var y = null;
    consloe.log(y); // Output on the console for development and testing
</script>

​ 2. Variables can be defined repeatedly, and the following will overwrite the previous one

​ 3. You can also define variables without var. by default, attributes are added to window objects

name = 'Zhang San'// Equivalent to window name = 'Zhang San';

'use strict'   // Strict code mode (variables must be defined before use)
var x = 10;
var y = 15;

4. If the defined variable has no assignment, the system will automatically assign the default value to 'undefined'

​ 5. A statement can end with or without a semicolon; If multiple statements are written on the same line, they must be separated by semicolons.

​ 6. When writing code, except that Chinese punctuation can be used in the string, English punctuation can only be used anywhere else.

12. Data type

Data type refers to the way memory is stored.

Divided into:

1) basic data type

number: numeric

Used to represent a number, usually used for addition, subtraction, multiplication and division.
It is divided into integer type and floating point type. (decimal places can float)
100 (decimal)
0123 (octal)
0xae12 (HEX)
isNaN() is used to determine whether it is non numeric
Number -- not true
false - number


string character type

A character (which can be a number, letter, punctuation mark, Chinese character, etc.) enclosed in quotation marks (single or double quotation marks are OK, they are no different)
'abc'
"abc" makes no difference
If you want to output quotation marks, add an escape character
"a'bc"

Null null value

Indicates the address of an empty object. The specified object is null

boolean type

Indicates true or false

Undefined undefined

Indicates that a variable is defined, but if no value is assigned to this variable, the default value is undefined

2) Reference data type

Object object type

Used to declare or store an object (object, function, regular, character, value, etc.)

var a = new Number(10) ;
var obj ={
	sno: '007',
	sname: 'Zhang San'
}

//a and obj are both object-oriented

13. Operator

1) Arithmetic operator

>+ - * / %   Addition, subtraction, multiplication, division and remainder 

Note: when calculating the remainder, if the previous number is negative, the result is also negative. (the effect is as follows)

Self increasing / self decreasing

++x --x pre auto increment / Auto decrement: the effect is to auto increment / Auto decrement before operation
x++ x -- post auto increment / Auto decrement: the effect is to calculate first and then auto increment / Auto decrement

Examples are as follows:
var x = 10;

2) String operator

+: used to implement string connection

console.log('aaa' + 'bbb');   //aaabbbb
console.log('aa a' + 'bbb');  //aa abbb
console.log(123 + 'bbb');   //When the character type is 123b, the value type is automatically converted to BBB
console.log(true+ 'bbb');  //truebbb principle is the same as above
console.log(undefined+ 'bbb');  //The undefined principle is the same as above

Output string length:

consloe.log('aaa'.length); //  3

3) Relational operator

>   <    >=    <=    ==    ===  !=  !==

The returned result can only be true or false
Comparison method:
a. Compare the values and compare their sizes
b. Character comparison, compare ascii code values (if it is a string, compare by bit. If the first letter is larger than the size, the following characters will not be compared)
c. Compare Chinese characters and compare the size of unicode coding value
You can get the encoded value through charCodeAt()

Common ascii code values:

ascii code of A: 65

ascii code of a: 97

0:48 enter: 13 ESC: 27

console.log('a'<'hdhdhdd'); //true
console.log('a'<'FGSG'); //false

console.log('Zhang San'<'Li Si'); //true

consloe.log('Zhang San'.charCodeAt(0));// 24352 find the code of 'Zhang'
consloe.log('Li Si'.charCodeAt(0)); //26466 find the code of 'Li'
console.log('100'== 100) //true
console.log('100' === 100) //false

console.log('3845'>'Zhang San') //fasle 'sheet' 24352

Comparison rule:

Some symbols < numbers < uppercase characters < lowercase letters < Chinese characters

4) Logical operator

Logical operators are:! & &|| Three.
Generally, the logical value true or false is returned, but other results may also be returned in js
! : Logical non (negation) (monocular / unary operation)
!true -> false
!false -> true
&&: logical and (binocular / binary operation)
As long as one operand is false, the result is false.
||: logical or (binocular / binary operation)
As long as one operand is true, the result is true.

a key:

console.log(!123) //false values other than 0 are generally converted to true! 123=false
console.log(!0) //true a value of 0 is generally converted to false,! 0 = true
console.log(! 'abc') / / false conversion of non null characters to true
console.log(! ') / / true null character converted to false

!!!!! The object or array is converted to true whether it has a value or not!!!
console.log(!{}) //false
console.log(![]) //false
console.log(!{name: 'Lao Wang'}) / / false
console.log(![1,2,3]) //false

if(123) {/ / 123 here is automatically converted to true, that is, the condition is true
}

be careful:

Logic and operation&&

If either operand between two operands is a non logical value

If the result of the first operand is true, the value of the second operand is returned;

If the result of the first operand is false, the first operand value is returned

console.log(123 && 0)  // 0
console.log(123 && 10 + 20) // 30
console.log(123 && 'abc') //abc
console.log(123 && []) // []
console.log(false && [] ) //false
console.log(0 && 'abc')  //0

In logic or operation

If either operand between two operands is a non logical value

If the result of the first operand is true, the value of the first operand is returned;

If the result of the first operand is false, the second operand is returned

console.log(true || false) //true
console.log(123 || 0) //123
console.log(123 || 0+10) //123
console.log(fale || []) //[]
console.log(0 || 'aga')  /aga

be careful:

Short circuit operation:

During A. & & operation, if the first operator is false, the second operand does not need to be calculated, and the result returns false

b. |, if the first operator is true, the second operand does not need to be calculated, and the result returns true

var x = 100;
var y = true && ++x;
console.log(x,y); //101 101
var x = 100;
var y = false && ++x;   // Short circuit, the following + + x cannot be executed
console.log(x,y); //100 false
var x = 100;
var y = false || ++x;
consloe.log(x,y); // 101 101
var x = 100;
var y = true || ++x;  //Short circuit, the following + + x cannot be executed
consloe.log(x,y); // 100 true

5) Bitwise operator

Not for the time being

6) Ternary operator (?)

Syntax:
Expression 1? Expression 2: expression 3
If expression 1 holds, the result of expression 2 is returned
If expression 1 does not hold, the result of expression 3 is returned

Tips:

The ternary operation is equivalent to the double branch structure in the if statement.

If expression 2 or expression 3 is complex, it is recommended to implement it with if statement or switch statement.

14. Process control

js is a process oriented and object-oriented interpretive language.
Process oriented: execute in order of code writing (OOP).
js is also a structural language.
The structure of js is divided into sequence structure, branch (condition / selection) structure and loop structure.
Sequential structure: execute in sequence according to the writing order of the code, generally including initialization, assignment, input / output and other statements.
Conditional structure: it is implemented with if or switch statements, in which the code is executed conditionally.
Loop structure: a part of the code is executed repeatedly within the specified condition range, which is implemented by the for/for... in/forEach/while/do... While statement.

1) Conditional structure

a. Single branch
Syntax:
if (condition){
Statement / statement group;
}
If the condition holds, the statement or statement group will be executed; If the condition does not hold, execute the next statement of if

b. Multi branch
Syntax 1:
if (condition 1){
Statement / statement group;
}
else if (condition 2){
Statement / statement group;
}
else if (condition 3){
Statement / statement group;
}
else {
Statement / statement group;
}

Case statement: switch

Syntax:
Switch (condition){
case expression 1: statement 1 or statement group 1; [break;]
case expression 2: Statement 2 or statement group 2; [break;]
case expression 3: Statement 3 or statement group 3; [break;]
case expression 4: statement 4 or statement group 4; [break;]
...
case expression n: Statement 3 or statement group n; [break;]
default: statement n+1 or statement group n; [break;]
}
explain:

If the conditions in switch are met,

Execute the statement after the corresponding case until a break is encountered;

In other words, without break, the following statements will be executed and fall into an endless loop

If the conditions are not met, execute the statements in default

be careful:

var score = parseInt(prompt('Please enter student name: ');
The data of prompt is text type
parseInt converts a type to a numeric type
Of course, you can also convert parseFloat to floating point

var rs = '';
switch(Math.floor(score/10)){  //Math.floor() rounded down
case 0:
case 1:
case 2:
case 3:
case 4:
case 5: rs = 'fail,';break;
case 6:
case 7: rs = 'pass';break;
case 8: rs = 'excellent';break;
case 9:
case 10: rs = 'Very excellent' ;break;
}

If there is no content in the previous case, it can be omitted;

tips:
The difference between switch and if:
switch deals with simple condition judgment, while if deals with complex conditions
switch can handle it, and if can handle it
if can't handle it, switch can't handle it
If you can handle it, swith is relatively concise.

Syntax:

for([Variable initial value];[condition];[step]){
		[Circulatory body];
		[continue];
		[break;]
	}
	
Variable initial value, condition and step size can be placed elsewhere;
	For example, calculate 1+2+3...+100
1)
	var sum = 0;
	for(var i=1;i<=100;i++){
		sum += i;
	}
	
2)
	var sum = 0, i= 1;
	for(;i<=100;i++){
		sum += i;
	}
	
3)
	var sum = 0, i= 1;
	for(;i<=100;){
		sum += i;
		i++;
	}
3)
	var sum = 0, i= 1;
	for(;;){
		if(i<=100){
			sum += i;
			i++;
		}
		else{
			break;   //Note that if you don't add break here, you will fall into a dead circle
		}	
	}

b. While

Output the sum of the first 100 numbers
var sum = 0, i = 1;
while(i<=100){
	sum+=i;
	i++;
}

**Difference between and if: * * the number of cycles is unknown.

c. Until type cycle

Output the sum of the first 100 numbers
var sum = 0, i = 1;
do {
	sum+=i;
	i++;
}while(i<=100);

Difference between and while:

Execute the statement first and then judge the condition,

There is no difference in essence, but if the conditions are not met, do... While is executed at least once, and while is not executed at all.

d. Array and object traversal (described later)

for ...in

forEach

Summary:

for can only be used when the number of cycles is known;
while and do... while can be used when the number of cycles is known or unknown. Generally, the number of cycles is known, and more for is used
for... in is used to traverse objects and arrays;
forEach() is used to traverse the array.
for can also be used to traverse arrays, but the performance is poor.

3) break and continue statements

break statements can be used in switch statements and loop statements (except for forEach loops) to jump out (end) the loop.
The continue statement can only be used in loop statements (except for forEach), which means to end this loop and continue the next loop.
be careful:
break and continue statements must exist separately, and no other code can be added later.
break and continue statements generally exist in if statements

//break statement 
//Requirement: find the number between 100-999 that can be divided by 3 and 7.
for(var i=100;i<1000;i++){
	if(i % 3 == 0 && i % 7 == 0){
		document.write("100-999 The numbers that can be divided by 3 and 7 are:"+i+'');
		break;  //If break is added here, the above statement will be executed only once, that is, there is only one number.
	}
}
//continue Statement 
//Requirement: find the number between 100-999 that can be divided by 3 and 7.
for(var i=100;i<1000;i++){
	if(i % 3 == 0 && i % 7 == 0){
		document.write("100-999 The numbers that can be divided by 3 and 7 are:"+i+'');
		continue;  //Terminate this cycle and continue the next cycle. You cannot execute many subsequent statements
		alert('hellow'); // This statement cannot be executed, and the statements after continue will not be executed
	}
}

Keywords: Javascript Front-end

Added by underparnv on Tue, 08 Feb 2022 04:04:43 +0200