The code structure
Js understands line breaks as “implicit” semicolons. This is also known as automatic semicolon insertion
alert('Hello')
alert('World')
Copy the code
Exception:
// If a line ends with a plus sign "+", this is an "incomplete expression" and js does not think a semicolon is needed.
alert(3 +
1
+ 2);
// Result output 6
alert("All fine now");
[1.2].forEach(alert)
// Print All fine Now and an error
// the expression before [] is also considered incomplete
Copy the code
(function() {
'use strict';
let a = 'dd'}) ()Copy the code
Strict mode
Use strict, you have to be at the top to have global effects and the console needs to use self-executing functions
(function() {
'use strict';
a = '111' / / / complains
/ /... Your code...}) ()Copy the code
Variable naming
Variable names must contain only letters, numbers, and the symbols $and _. The first character must be a non-digit. Non-english letters allowed, but not recommended, e.g. Let Lee = ‘x’
The data type
Seven primitive types and one reference type
Number
Regular numbers and special values Infinity, -infinity, and NaN Infinity are infinite in mathematics and can be plus or minus
1 / 0// Infinity
Infinity// Can be accessed directly
Copy the code
NaN represents a calculation error. It is the result of an incorrect or undefined mathematical operation
"not a number" / 2// NaN, such a division is wrong
"not a number" / 2 + 5// NaN
Copy the code
BigInt
The “n” at the end indicates that this is a BigInt
const bigInt = 1234567890123456789012345678901234567890n;
Copy the code
String String
Double quotes: “Hello”. Single quotes: ‘Hello’. Back quotes: Hello
// We can use ${} to calculate
let a = 'Joe'
`the result is ${a} The ${1 + 2}`// the result is 3
Copy the code
Boolean Indicates the Boolean type
“Null” value
The special null value does not belong to any of the above types and constitutes a separate type containing only null values: let age = null; In contrast to other programming languages, null in JavaScript is not a “reference to a nonexistent object” or a “null pointer.” Null in JavaScript is simply a special value that represents “none”, “empty”, or “value unknown”. The code above indicates that age is unknown.
undefined
The special value undefined is of type like null. Undefined means not assigned. If a variable is declared but not assigned, its value is undefined:
let age;
alert(age); / / the pop-up "undefined"
let age = 100;
// Change the value to undefined
age = undefined;
alert(age); // "undefined"
Copy the code
Symbol is used for unique identifiers.
Object Complex data type
typeof
Typeof operator returns the typeof the parameter as operator: typeof x. Function form: typeof(x)
typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2) // null is definitely not an object. Null has its own type, which is a special value.
typeof alert // "function" (3)
Copy the code
The result of typeof Alert is “function”, because alert is a function in the JavaScript language. We’ll learn about functions in the next chapter; there is no specific “function” type in the JavaScript language. Functions belong to type object. But Typeof treats functions differently and returns “function”. This is also a problem from the early days of the JavaScript language. This behavior is technically incorrect, but it is very convenient in real programming.
Type conversion
- Definition: Operators and functions automatically convert the values assigned to them to the correct type
- Operators such as + /, shows the call Number (content), “1” + “2” = > Number (” 1 “) + Number (” 2 “)
- Functions such as alert will display the call String(content), alert(1) => alert(“1”)
Basic data type conversion
- String type
String(value)
- Numeric types
- Number(value)
- undefined => NaN
- null => 0
- true / false => 1 / 0
- String => “Read as is” string. Whitespace at both ends is ignored. The empty string becomes 0. NaN is output if the conversion fails.
- Boolean type
- 0, null, undefined, NaN, “” => false
- Other values, “”(including whitespace strings) => true
let a
if (a) { //false
}
if("") { //false
}
if("") { //true
}
Copy the code
Basic operators, math
Unary operator
x = -x;
alert( x ); // the unary negative operator is in effect
Copy the code
Binary operator”
let x = 1, y = 3;
alert( y - x ); // 2, the binary operator minus is subtracted
Copy the code
Mathematical operations:
Addition + subtraction – multiplication * division /,
Take more than %
The result of a % b is the remainder of a divided by B.5 % 2 ); // the remainder of 5 divided by 2
alert( 8 % 3 ); // 2, remainder of 8 divided by 3
Copy the code
Exponentiation * *
It’s just a square, and it supports square roots
/ / square
alert( 2习皇帝2 ); // 4 (2 * 2)
alert( 2习皇帝3 ); // 8 (2 * 2 * 2)
alert( 2习皇帝4 ); // 16 (2 * 2 * 2 * 2)
/ / square root
alert( 4* * (1/2));// 2 (the same thing as the square root)
alert( 8* * (1/3));// 2 (1/3 power is the same as cube root)
Copy the code
Binary operator + connection string
Rule: If there is a String, go to String(value) first, and go to Number(value) otherwise.
alert( '1' + 2 ); / / "12"
alert( 2 + '1' ); / / "21"
alert(2 + 2 + '1' ); // "41", not "221"
alert( true + true ); / / 2
Copy the code
Binary operator – * /
-
- / Is handled by Number(value)
The unary operator +
Digital transformation
// Not valid for numbers
let x = 1;
alert( +x ); / / 1
let y = -2;
alert( +y ); / / - 2
// Convert non-numbers
alert( +true ); / / 1
alert( +"" ); / / 0
Copy the code
priority
priority | The name of the | symbol |
---|---|---|
17 | Unary plus | + |
17 | Unary minus | – |
16 | exponentiation | 习皇帝 |
15 | Multiplication sign | * |
15 | devide | / |
13 | A plus sign | + |
13 | A minus sign | – |
3 | The assignment operator | = |
1 | The comma | . |
Chain assignment
let a, b, c;
a = b = c = 2 + 2;
alert( a ); / / 4
alert( b ); / / 4
alert( c ); / / 4
Copy the code
In situ modification
let n = 2;
n = n + 5;
// equivalent to operator +=
let n = 2;
n += 5;
Copy the code
Increase/decrease automatically
The pre-form returns a new value, but the post-form returns the original value (before addition/subtraction).
let counter = 0;
alert( ++counter ); / / 1
let counter = 0;
alert( counter++ ); / / 0
let counter = 1;
alert( 2 * counter++ ); // 2, because counter++ returns "old value"
Copy the code
Note: 5++ is an error
An operator
- Bitwise operators treat operators as 32-bit integers and operate on their binary representation.
- Bitwise and (&)
- Bitwise or (|)
- Bitwise xor (^)
- Bitwise non (~)
- Shift left (<<)
- Move right (>>)
- Unsigned right shift (>>>)
The comparison of the value
All comparison operators return a Boolean value:
String comparison
The first comparison, if the same continues, compares according to Unicode encoding order
'Z' > 'A'// true
'Glow' > 'Glee'// true
'Bee' > 'Be'// true
Copy the code
Comparisons between different types
JS will first convert it to a number and then determine the size
'2' > 1// true, the string '2' is converted to the number 2
'01'= =1// true, the string '01' is converted to the number 1
'a'= =1// Always false because 'a' => Number('a') = NaN, NaN and any Number is false
'a' > 1//false
'0'= =false//true
' '= =false//true
Copy the code
Strictly equal
' '= = =false // false
Copy the code
Null is compared with undefined
Undefined and null do not perform any type conversions in equality checks ==,
Number(null) => 0 Number(undefined) => NaN
null= = =undefined // false
null= =undefined // false //js is specially treated, and is only true for non-strict equality
null < undefined // False is normally converted to a Number, Number(null) => 0 Number(undefined) => NaN
null > 0 // (1) false
null= =0 // (2) false
null> =0 // (3) true
"0"= = +"\n0\n" / / true here + execution first Number (" \ n0 \ n ") = > 0, and then compare "0" = = 0, Number (" 0 ") = = 0
Copy the code
# # to summarize
-
Except for strict equality ===, we need to be careful with all comparisons involving undefined/null.
-
Never use >= > < <= to compare a variable that may be NULL /undefined unless you know exactly what you are doing. For variables whose values may be null or undefined, check their values as required.
-
The comparison operator always returns a Boolean value.
-
Strings are compared, character by character, in dictionary order.
-
When different types of values are compared, they are converted to numbers (excluding strict equality checks) before being compared.
-
Under non-strict equality ==, null and undefined are equal and not equal to any other value.
-
When using > or < for comparison, note that the variable may be null/undefined. A better method is to separately check whether the variable is equal to null/undefined.
Conditional branch
? Ternary operation, lower priority
let age = 1
let a = (age > 18)?true : false; //
// The parentheses can be omitted
let a = age > 18 ? true : false;
Copy the code
Multiple ‘? ‘
let age = prompt('age? '.18);
let message = (age < 3)?'Hi, baby! ' :
(age < 18)?'Hello! ' :
(age < 100)?'Greetings! ' :
'What an unusual age! ';
alert( message );
/ / equivalent to the
if (age < 3) {
message = 'Hi, baby! ';
} else if (age < 18) {
message = 'Hello! ';
} else if (age < 100) {
message = 'Greetings! ';
} else {
message = 'What an unusual age! ';
}
Copy the code
Logical operator
Boolean(value) conversion is automatically performed
| | (or)
1. The or operation finds the first truth value
- result = value1 || value2 || value3;
- Evaluate the operands from left to right.
- Each operand is converted to a Boolean value as it is processed. If the result is true, the calculation is stopped and the initial value of the operand is returned.
- If all operands have been evaluated (that is, the conversion result is false), the last operand is returned.
// intermediate true returns the intermediate value directly
let firstName = ' ' ,lastName = 'bbb' ,lastName = ' ' ;
firstName || lastName || lastName || "aaa"); // bbb
// Return the last one directly
let firstName = ' ' ,lastName = ' ' ,lastName = ' ' ;
firstName || lastName || lastName || "aaa"); // aaa
Copy the code
1. Short-circuit evaluation
Operands can be variable assignments or function calls
true || alert("not printed");
false || alert("printed");
Copy the code
- In the first line, or the operator | | to meet a true immediately stop operation, so the alert is not running.
- Sometimes people use this feature to execute commands only when the condition on the left is false.
&& (with)
And search for the first false value
1 && 2 && 3 3 / / output
Copy the code
At the same time && and | |
Use (1 && 2) to wrap the “and” content as follows:
0 || 2 && 0 || 3 && 4
/ / equivalent to the
0| | -2 && 0) | | (3 && 4) / / = > 0 | | 0 | | 4 results of 4
Copy the code
! (a)
Boolean return opposite value (value), the highest priority in all logical operators, in && and | | before execution. Two non-operations!! Sometimes used to convert a value to a Boolean type:
alert( !!"non-empty string" ); // true
alert( !!null ); // false
Copy the code
Null-value merge operator ‘?? ‘(new symbol)
The first argument is not null/undefined, then?? Returns the first argument. Otherwise, return the second argument.
let a,b;
a ?? b
/ / equivalent to the(a ! = =null&& a ! = =undefined)? a : b;// continuous judgment
let firstName = null;
let lastName = null;
let nickName = "Supercoder";
// Display the first defined value:
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
Copy the code
?? Compared with the | |
let height = 0;
alert(height || 100); // 100 // Boolean(0) = false
alert(height ?? 100); // 0 // undefined or null
Copy the code
priority
?? In = and? Evaluates before, but after most other operators (for example, + and *).
For security reasons, JS forbids?? Operator with && and | | operators are used together, unless you use parentheses to specify the priority.
let x = 1 && 2 ?? 3; // Syntax error
let x = 1 && (2 ?? 3); / / normal
Copy the code
Loops: while and for
while
while (i ! = 0) while (I) :
let i = 3;
while (i) { // When I becomes 0, the condition is false and the loop terminates
alert( i );
i--;
}
// Single-line loop bodies do not need braces
while (i) alert(i--);
Copy the code
“Do… While “loop
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
Copy the code
for
// Inline variable declarations
for (let i = 0; i < 3; i++) {
alert(i); / / 0, 1, 2
}
alert(i); // Error, there is no such variable.
// Can be defined externally
let i = 0;
for (i = 0; i < 3; i++) { // Use existing variables
alert(i); / / 0, 1, 2
}
alert(i); //3, visible because it is declared outside the loop
// omit the statement segment
/ / omit the begin
let i = 0; // We have declared I and assigned it a value
for (; i < 3; i++) { // The "begin" statement is no longer required
alert( i ); / / 0, 1, 2
}
/ / omit the step
let i = 0;
for (; i < 3;) {
alert( i++ );
}
/ / equivalent to the
while (i < 3)
// omit all
for (;;) {
// Infinite loop
}
Copy the code
break/continue
Break terminates the loop, continue continues the next loop disallows break/continue in ‘? ‘on the right side of the
(i > 5)? alert(i) :continue; // continue is not allowed at this position
Copy the code
Tags: XXX
XXX: definition, break outer must loop inside
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
let input = prompt(`Value at coords (${i}.${j}) `.' ');
// If the string is empty or cancelled, break out of both loops.
if(! input)break outer; / / (*)
// Do something with the value...
}
}
alert('Done! ');
// A line break declaration is also possible
outer:
for (let i = 0; i < 3; i++) {... }Copy the code
Title: Repeat input until the correct value is greater than 100
let input
do {
input = prompt("Please enter numbers greater than 100")}while(input <= 100 && input)
Copy the code
Title: Output Prime (Prime)
let n = 10
outer: for(let i = 2; i <= n; i++){let j = 2;
while(j<i ){
if(i%j === 0) { // Currently not prime
// console.log(" Currently not prime ", I)
continue outer;
}
j++
}
console.log("Prime",i)
}
Copy the code
switch
- If equal, the switch statement executes the block of code under the corresponding case until the nearest break statement is encountered.
- If no case matches, the default code block is executed (if default exists).
// The contents of the case are strictly matched ===
let a = 2
switch(a) {
case '2': alert("ddd")}// Invalid 2 === '2' => false
Copy the code
Any expression can be a parameter to a switch/case
let a = "1";
let b = 0;
switch (+a) {
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
break;
default:
alert("this doesn't run");
}
Copy the code
The case group
let a = 3;
switch (a) {
case 4:
alert('Right! ');
break;
case 3: // (*) The following two cases are grouped together
case 5:
alert('Wrong! ');
alert("Why don't you take a math class?");
break;
default:
alert('The result is strange. Really.');
}
Copy the code
function
A local variable
function showMessage() {
let message = "Hello, I'm JavaScript!"; // Local variables
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- error! Variables are local variables of a function
Copy the code
External variables
let userName = 'John';
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
showMessage(); // Hello, John
Copy the code
Local variables and external variables exist at the same time, internal variables are preferred
parameter
Functions can modify arguments, but do not see the changes outside the function, which modifies the copied copy of the value of the variable:
function showMessage(from, text) {
from = The '*' + from + The '*'; // Make "from" look elegant
alert( from + ':' + text );
}
let from = "Ann";
showMessage(from."Hello"); // *Ann*: Hello
// The function modifies a local copy of the same "from" value.
alert( from ); // Ann // no change in value
Copy the code
The default value
No parameter is set. The default value is undefined.
// You can specify the default
function showMessage(from, text = "no text given") {
alert( from + ":" + text );
}
showMessage("Ann"); // Ann: no text given
Copy the code
Backup default parameters
//1
function showMessage(text) {
if (text === undefined) {
text = 'empty message';
}
alert(text);
}
showMessage(); // empty message
/ / 2. | | operators
function showMessage(text) {
text = text || 'empty'; . }//3. Null merge operator??
function showCount(count) {
alert(count ?? "unknown");
}
showCount(0); / / 0
showCount(null); // unknown
showCount(); // unknown
Copy the code
return
Do not add a new line between return and return value
A return with a null value or a function without a return returns undefined