2 Basic JS syntax
2.0 constant
Constants, also known as literals, are a representation method of fixed values, that is, literal meaning. You can recognize what you see. Data of various types, such as numbers, strings, arrays, and JSON objects, all have their own literal representation.
-
Numeric literal: A common mathematical representation of numbers, written directly without any special symbols.
-
String literals: string is a human language, words, including various numbers, symbols; Enclosed by double or single quote pairs; The contents of the string are delimited between the same quotation marks. In the string, some characters need to be escaped, such as \n (newline), \t (TAB), “(quotation marks).
console.log("I can speak English and get first in the exam."); // Display the quotes directly
console.log(1); // represents the literal 1
console.log("1"); // Represents the character string 1
console.log("This is \n a quotation mark \" and a backslash \\"); // Escape characters
Copy the code
2.1 variable
var message; // define a variable named message
var message = "hi"; // Define the message variable and assign it to a string value "hi"
Copy the code
var message = "hi", found = false, age = 29;
// Use one statement to define multiple variables
Copy the code
-
Variables
- A container that can be used to hold any type of data
- The ECMAScript variable is
Loosely typed
- The variable name must follow
Identifier naming conventions
-
Declaration of variables
- It’s the definition of a variable that you can store data into
- Variables must be declared first (using keywords)
var
) before use - Var is used to declare a variable that has no initial value. Its value is set to undefined in advance
- Attempts to access an undeclared variable display RefersnceErmor error
- Redeclare an assigned variable without losing its value
-
Variable declaration promotion (reactive)
- Another special aspect of JS variables is that they can refer to a later declaration without throwing an exception
- Variables will be “up” or promotion to all the functions and statement before, after ascending the variable returns undefined values, so even after use or reference to a variable declaration and initialization, will still get undefined values, but variables, only improve definition, not ascend assignment, equivalent to define only reference, not the assignment, Output is undefined
console.log(a); / / to use first
var a = 125; / / after the definition
/ / equivalent to
var a; / / definition first
console.log(a); / / to use again
a = 125; / / after the assignment
Copy the code
2.2 Data Types
The data type of JS is a dynamic data type, which is reflected in the variable. The data type of a variable changes with the type of the data stored internally. The data type of a variable is the data type of the data stored internally
2.2.1 Undefined type
var message;
alert(message == undefined); //true
Copy the code
- Undefined has only one value, that is, if a variable is declared with var but not initialized, its value is Undefined
- A variable defined as undefined is not the same as an undefined variable
- The Typeof operator returns undefined for both uninitialized and undeclared variables
2.2.2 Null type
var car = null;
alert(typeof car); // "object"
Copy the code
- The Null type has only one value, representing an empty object pointer ==, and returns “object” when the typeof operator is used to detect Null values.
- If you define a variable that will be used to hold an object in the future, it is best to initialize the variable to NULL rather than some other value, so that you can check the null value directly to see if the corresponding variable already holds a reference to an object
- In fact, undefined is derived from null
- The variable == can be emptied by setting its value to null
2.2.3 Boolean type
var booleanValue = true;
alert(typeof booleanValue); // "Boolean"
Copy the code
Boolean types have only two literals, true and false, but all types of values in ECMAScript have values equivalent to these Boolean values. To convert a value to its corresponding Boolean, call the transformation function Boolean(), as shown in the following example:
The data type | The value converted to true | Convert to a value of false |
---|---|---|
Boolean | true | false |
String | Any non-empty string | “” (empty string) |
Number | Any non-zero numeric value (including infinity) | 0 and NaN |
Object | Any object | null |
Undefined | N/A (not applicable) | undefined |
2.2.4 Number type
/*-------------- integer literals -----------*/
// Decimal: The most basic numeric literal format, entered directly in code
console.log(100);
console.log(-12);
// octal: the prefix is 0, 0O, 0O. If 0 is used as the prefix, the value beyond the range will be directly converted to micro decimal display. If the prefix is 0O /0O, an error message is displayed when the value exceeds the specified value range
console.log(071); // represents an octal number (71)
console.log(089); // Represents a decimal number (89)
console.log(0o89); console.log(0O89); // Display error
// Hexadecimal: the prefix is 0x or 0x. If the prefix exceeds the specified value range, an error message is displayed
console.log(0x5c);
console.log(0x5g); // Display error
/*-------------- floating point number area -----------*/
// All floating point numbers are expressed in decimal
console.log(3.14159);
console.log(10.0); // Is parsed to the integer 10
console.log(0.618);
console.log(618.); //表示0.618
console.log(1.); // No number after the decimal point will be resolved to 1
console.log(-618.); / / - 0.618
console.log(42356.89);
console.log(0.4235689 e5);//e5 means x 10^5, and the result is still 42356.89
/*-------------- Special value -----------*/
// Infinity: the computing power of the computer is limited. If it is greater than or less than a certain critical point, the computer cannot calculate a specific number, and will directly output an Infinity or -infinity value, which cannot continue to participate in the next calculation
console.log(8.6 e987654322344677807); / / show the Infinity
console.log(-8.6 e98765056760544387); / / show - Infinity
//NaN (not a number) : not a number, indicating that the number can no longer be represented in the normal numerical form, not a normal meaning of the number, but still a literal number
console.log(0/0); / / display NaN
console.log(12/0); / / display NaN
Copy the code
- All octal and hexadecimal values are converted to decimal values when arithmetic is performed
- The highest accuracy of floating-point values is ==17 decimal places ==, but some floating-point calculations have the problem of rounding errors, a common problem with floating-point calculations using IEEE754 values, as well as in other languages
2.2.5 type String
-
String: Used to represent a character sequence consisting of zero or more 16-bit Unicode characters
var firstName = "Nicholas"; var lastName = 'Zakas'; var lastName = 'Nicholas"; // Syntax error (left and right quotes must match)Copy the code
-
Character literals: Also called escape sequences, used to represent non-print characters and for other purposes
var text = "This is the letter sigma: \u2764."; // The escape character is ❤ alert(text.length); // The length of any string can be obtained by accessing its length property, output 28 Copy the code
Once strings are created, their values cannot be changed. To change the string held by a variable, first destroy the original string and then populate the variable with another string containing the new value, as follows
var lang = "Java"; lang = lang + "Script"; /* Redefines the value of lang as a combination of "Java" and "Script", i.e. "JavaScript" */ Copy the code
2.2.6 Object type
2.2.7 Data conversion
2.2.7.1 turn Number
// Number() : for any data type
var a = Number(null), / / 0
b = Number(undefined), //NaN
c = Number(true), / / 1
d = Number(false), / / 0
e = Number("Eight"), / / - 8
f = Number("+ 8"), / / 8
g = Number("000011"), //11 (ignore 0)
h = Number("0xf"), //15 (16 to 10)
i = Number(""), //0 (blank content)
j = Number("12 + 3"), //NaN(presence symbol)
k = Number("12-3"), //NaN(presence symbol)
l = Number("a123"), //NaN(there are letters)
m = Number("12.."), //NaN(with decimal point)
n = Number("123"), //123(ignore space)
o = Number("Hello world!"), //NaN(there are letters, Spaces, symbols)
// parseInt() : returns only integers, missing decimal parts, specified cardinality, can be converted to base
var A = parseInt("123blue"), / / 123
B = parseInt(""), //NaN
C = parseInt("Infinity"), //NaN
D = parseInt("12abc"), //12(ignores characters)
E = parseInt("a12bc"), //NaN(header is not number, recognition error)
F = parseInt("0xAF".16), / / 175
G = parseInt("AF".16), / / 175
H = parseInt("AF"), //NaN(error specifying base)
I = parseInt("10".2), //2 (binary parsing)
J = parseInt("10".8), //8 (octal)
K = parseInt("10".10), //10 (in decimal)
L = parseInt("10".16), //16 (hexadecimal)
M = parseInt(22.5), / / 22
N = parseInt(5.2 e10); / / 5
// parseFloat() : converts a string to a floating point number with a decimal
var A1 = parseFloat("12.23"), / / 12.23
A2 = parseFloat("12.23.34"),/ / 12.23
A3 = parseFloat(12.23 "AAA"),//12.23(tail character ignored)
A4 = parseFloat("12.3 + 123");//12.3(omit trailing characters)
Copy the code
Turn 2.2.7.2 String
// console.log() : null and undefined directly use the console output to change to String
console.log(null); //"null"
console.log("Hello"+null); //"Hellonull"
console.log(undefined); //"undefined"
console.log("Hello"+undefined); //"Helloundefined"
// toString()
var a = true;
var aStr = a.toSting(); //"true"
var b = 11;
var bStr = b.toSting(); / / "11"
// String() : Can convert any type of value to a String
var W = 10;
var X = true;
var Y = null;
var Z; // undefined undefined
alert(String(W)); 10 "/ /"
alert(String(X)); //"true"
alert(String(Y)); //"null"
alert(String(Z)); //"undefined"
Copy the code
Since null and undefined have no toString() methods, only String() functions can be used
Turn 2.2.7.3 Boolean
Boolean() : Can convert most types of values to Booleans
// Most booleans return true
// The following 6 cases are converted to Boolean and the result is false
console.log(Boolean(0)); //false
console.1og(Boolean("")); //false
console.1og(Boolean(false)); //false
console.1og(Boolean(NaN)); //false
console.1og(Boolean(undefined));//false
console.log(Boolean(null)); //false
Copy the code
2.3 the operator
Operators, or Operators, are the simplest form of initiating an operation
2.3.1 Unary operators
- Since the (
++
) the decrement (--
) : before “first ±1 then value”, after “first value then ±1” - Unary plus (
+
) reduction (-
) : equivalent to a plus or minus sign
2.3.2 Additive operators
- Addition,
+
) - Subtraction (
-
)
+ can be used as a concatenation string operation :(“OX”+”456” → OX456)
2.3.3 Multiplier operator
- Multiplication (
*
) - Division (
/
) - Mod mod (
%
)
2.3.4 Assignment operator
- Assignment operator (
=
) : Assigns values on the right to variables on the left - Compound assignment operator:
Add + =, etc
- = reduction, etc
By such as * =
In addition to / =
More than % =, etc
Shift to the left, such as < < =
There are signs shift right, etc. >>=
Unsigned right shift, etc. >>>=
var num = 10;
num = num + 10;
num += 10; // Same as the previous statement, compound assignment is just a simplification
Copy the code
When a compound assignment is performed, the part after the equal sign is the whole, such as y*=x-3 — >y=y*(x-3).
2.3.5 Comparison operators
- Relational operators (
>
<
> =
< =
) - Equal (
= =
Not equal (! =
) : only compares the value, does not compare the type, before the comparison automatically unified type - Congruent (
= = =
) incongruence (! = =
) : Values and types are compared
All comparison operators return a Boolean value (true and false)
Relational operators cannot be used together. (e.g. 1 <= num <= 5)
2.3.6 bit operators
- Bitwise and (
~
) - Bitwise and (
&
) - The bitwise or (
|
) - Bitwise xOR (
^
) - Shift to the left (
<<
) - Signed shift right (
>>
) - Unsigned right shift (
>>>
)
2.3.7 Boolean operators
- Logic is not (
!
) : No is no - Logic and (
&&
) : Two truths are true - Logic or (
||
) : True is true
For A&&B, when A is assumed to be false, no more operations are performed on B
2.3.8 Conditional operators
// (judge condition)? Meet output: Does not meet output
var max = (num1 > num2) ? num1 : num2;
Copy the code
2.3.9 Comma operator
Multiple operations can be performed in a single statement using the comma (,) operator.
var num1=1, num2=2, num3=3; // Declare multiple variables
var num = (5.1.4.8.0); // the value of num is 0 (multiple assignments return the last item in the expression)
Copy the code
2.3. Priority of X operation
From high to low: arithmetic operator → comparison operator → logical operator → “=” assignment symbol
Sibling operation: proceed from left to right, with multiple brackets from inside out
2.3. Implicit conversion of ⅺ
Operation between numbers and purely numeric strings, == = except for the + sign ==, using any other operator will automatically convert the string to a number. Any mathematical operation involving other data types will be implicitly converted. This process is private and does not require methods such as parseInt
console.log(12+"2"); // The result is 122
console.log(12-"2"); // Result is 10
console.log(12*"2"); // Result is 24
console.log(12/"2"); // The result is 6
console.log(12%"2"); // The result is 0
console.log("12"%"2"); // The result is 122
Copy the code
Other implicit conversions- can be converted into0 : "".null.false- can be converted into1 : true- can be converted intoNaN : "Non-empty string".undefined.NaN- can be converted intoInfinity: It depends on the situationCopy the code
2.4 the statement
Against 2.4.1 if – else statements
The condition statement == evaluates the Boolean value returned by condition. Statement1 is executed if true and statement2 if false.
// if (condition) statement1 else statement2
if (i > 25)
alert("Greater than 25."); // Single line statement
else {
alert("Less than or equal to 25."); // statements in code block {}
}
Copy the code
// if (condition1) statement1 else if (condition2) statement2 else statement3
if (i > 25) {
alert("Greater than 25.");
} else if (i < 0) { // Multi-layer nesting condition judgment
alert("Less than 0.");
} else {
alert("Between 0 and 25, inclusive.");
}
Copy the code
2.4.2 the do – while statement
The statement is executed once and then the expression is evaluated. If false is returned, the statement is executed again until true is returned.
// do {statement} while (expression);
var i = 0;
do {
i += 2;
} while (i < 10);
alert(i);
Copy the code
2.4.3 while statement
If the statement is true, the statement is executed once. After the statement is executed, the expression is evaluated again. If the statement is false, the statement is skipped and the statement continues.
// while (expression) statement
var count = 10;
var i = 0;
while (i < count) {
alert(i);
i++;
}
Copy the code
2.4.4 for statement
If true is returned, statement is executed. After statement is executed, post-loop-expression is executed. After statement is executed, post-loop-expression is executed. Then re-evaluate expression until it returns false before breaking out of the loop and continuing.
// for (initialization; expression; post-loop-expression) statement
var count = 10;
for (var i = 0; i < count; i++){
alert(i);
} // Performs the same function as the previous while block
Copy the code
- The for loop is another expression of the while loop, which does the same thing;
- Initialization can be defined externally without using the var keyword.
- Since there is no block-level scope in ECMAScript, variables defined inside the loop can also be accessed externally;
- Initialization expressions, control expressions, and post-loop expressions in for statements are optional (omitted), as in for (,,).
2.4.5 switch statement
If there is a match, execute the code block associated with the case. After execution, use break to break out of this case and prevent the next case from running. If there is no corresponding value, the code block associated with default is executed.
// switch (expression) {case A: statet1 break; case B: state2 break; default: state3}
switch (i) {
case 25:
alert("25");
break;
case 35:
alert("35");
break;
case 45:
alert("45");
break;
default:
alert("Other");
}
Copy the code
- Expression can use any data type, whether string or object;
- The value of each case does not have to be a constant; it can be a variable, or even an expression.
2.4.6 Break and continue statements
A == breakpoint statement == is used to precisely control the execution of code in a loop.
var num = 0;
for (var i=1; i < 10; i++) {
if (i % 5= =0) {
break; // Immediately break out of the loop and force the statement following the loop to continue
}
num++;
}
alert(num); / / output 4
Copy the code
var num = 0;
for (var i=1; i < 10; i++) {
if (i % 5= =0) {
continue; // The loop is restarted from the top of the loop
}
num++;
}
alert(num); / / output 8
Copy the code
2.4.7 label statement
A == label statement ==, which adds labels to code that can be referenced in the future by a break or continue statement. It is typically used in conjunction with loop statements such as the for statement to return to a specific location in the code.
// label: statement
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost; /* Exits the inner loop (using the variable j) and the outer loop (using the variable I) */
}
num++;
}
}
alert(num); / / 55
Copy the code
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
continue outermost; /* Force the loop to continue -- exit the inner loop and execute the outer loop */
}
num++;
}
}
alert(num); / / 95
Copy the code
From 2.4.8 the for in statement
An exact == iteration statement == is used to enumerate the attributes of an object.
// for (property in expression) statement
for (var propName in window) {
document.write(propName);
}
/* This shows all the properties of the window object in the BOM (variable in object). That is, each time the loop is executed, an attribute name that exists in the window object is assigned to the variable propName. This process continues until all attributes in the object have been enumerated. * /
Copy the code
Properties of ECMAScript objects have no order and are therefore unpredictable. All properties are returned once, but the order in which they are returned may vary from browser to browser.
If the iterated object is null or undefined, an exception is thrown.
2.4.9 with statement
The main purpose of scoping code to a particular object is to simplify the task of writing the same object multiple times.
// with (expression) statement;The original program// (contains multiple location objects)
var qs = location.search.substring(1);
var hostName = location.hostname;
varurl = location.href; Instead ofwith (location) { / / to simplify
var qs = search.substring(1);
var hostName = hostname;
var url = href;
}
Copy the code
Heavy use of the WITH statement degrades performance and makes debugging code difficult, so it is not recommended when developing large applications.
2.5 the function
Functions can encapsulate any number of statements and be executed anywhere and at any time when they need to be called. Function definitions do not specify whether or not to return a value, but can use a return statement to return a value.
function functionName (arg0, arg1, ...) {statements}
function sayHi(name, message) {
alert("Hello " + name + "," + message);
}
sayHi("Nicholas"."how are you today?");
/* This function outputs "Hello Nicholas,how are you today?" * /
Copy the code
function sum (num1, num2) {return num1 + num2; }
var result = sum(5.10);
function sum(num1, num2) {
return num1 + num2; // Stop and exit immediately after executing the return statement
alert("Hello world"); // Never execute
}
Copy the code
A return statement can also have no return value (return;). , the function returns undefined when it stops executing, but it is recommended that the function either always return a value or never return a value at all