Introduction to a,
1.1 history
Programmer Brendan Eich designed the first version of the language in 10 days in May 1995, with syntax from multiple sources.
- Basic syntax: borrowed from C and Java
- Data structure: Using Java as a reference, values are divided into raw values and objects
- Function usage: Borrowing from Scheme and AWK, using functions as first class citizens and introducing closures
- Prototype inheritance model: Borrow from Self
- Regular expressions: Borrow from Perl
- String and array handling: Take a page from Python
1.2 Basic Syntax
Statement: A statement is an operation performed to accomplish a task. Here is a line of assignment statements.
let a = 1 + 3;
Copy the code
Here, 1+3 is an expression, which refers to an expression used to obtain a return value. The difference between a statement and an expression is that the former is used to perform certain operations and generally does not require a return value. The latter, in order to get a return value, must return a value. Variable promotion.
The JavaScript engine works by parsing the code, retrieving all the declared variables, and then running them line by line. All declarations of variables are referred to as hoising at the head of the code and this is basically variables declared using the keywords var and function.
1.3 Ternary operators? :
It can be viewed as if… else… Short form for
1.4 Labels
The JavaScript language allows statements to be preceded by a label, which acts as a locator to jump to any point in the program, in the following format.
Label: statementCopy the code
Tags are often used in conjunction with break and continue statements to break out of a particular loop
top:
for (var i = 0; i < 3; i++){
for (var j = 0; j < 3; j++){
if (i === 1 && j === 1) break top;
console.log('i=' + i + ', j='+ j); }}Copy the code
The above code is a double loop block, followed by the break command with the top tag (note that top is not quoted), when the condition is met, directly out of the double loop. If the break statement is not followed by a label, you can only break out of the inner loop and enter the next outer loop. Used to jump out of a double loop
Second, data type
2.1 null, and undefined
In the first version of JavaScript, null was treated as an object just like in Java, and Brendan Eich decided that a value for “nothing” was better not an object. Second, JavaScript at the time did not include error handling, and Brendan Eich felt that if NULL was automatically turned to zero, it would be hard to spot errors. Therefore, he also designed a undefined, the difference is: null represents an empty object, when converted to a value of 0, undefined represents a “not defined here” original value, when converted to a value of NaN.
2.2 numerical
All numbers inside JavaScript are stored as 64-bit floating point numbers, and there are no integers at all in the underlying JavaScript language.
1 === 1.0 // true
Copy the code
The 64 binary bits of JavaScript, starting from the left:
- First bit: sign bit. 0 represents an integer and 1 represents a negative number
- Places 2 to 11 (total of 11 places) : exponential part
- The 13th to 64th digits (52 digits in total) : indicates the decimal part, that is, the significant number
The JavaScript Number object provides the MAX_VALUE and MIN_VALUE attributes, which return the maximum and minimum values that can be specified.
2.2.1 Positive and negative 0
One of avaScript’s 64-bit floating-point numbers is a symbolic bit. That means that every number has a negative value, even 0.
JavaScript actually has two zeros: a +0 and a -0, the difference being the sign bit of the 64-bit floating-point representation. They’re equivalent.
+0= = = -0 // true
0= = = +0 // true
0= = = -0 // true
(1 / +0) = = = (1 / -0) // false
Copy the code
And then the last one, because if you divide by positive zero you get plus Infinity, and if you divide by negative zero you get minus Infinity, those two things are not equal.
2.2.2 NaN
NaN stands for “non-number” and is mainly used when parsing a string to a number is wrong; 0 divided by 0 also yields NaN. NaN is not a separate data type; it belongs to Number.
2.2.3 Related methods
- ParseInt (): For numbers that are automatically converted to scientific notation, parseInt treats the scientific notation representation as a string, resulting in strange results that return only numbers or NaN.
parseInt(1000000000000000000000.5) / / 1
/ / is equivalent to
parseInt('1e+21') / / 1
parseInt(0.0000008) / / 8
/ / is equivalent to
parseInt('8e-7') / / 8
Copy the code
Note:
parseFloat(true) // NaN
Number(true) / / 1
parseFloat(null) // NaN
Number(null) / / 0
parseFloat(' ') // NaN
Number(' ') / / 0
parseFloat('123.45 #') / / 123.45
Number('123.45 #') // NaN
Copy the code
2.3 the string
A string can only be written on one line by default, and multiple lines will cause an error. If a long string must be split into multiple lines, use a backslash at the end of each line.
var longString = 'Long \
long \
long \
string';
longString
Copy the code
2.3.1 Strings and Arrays
Strings can be thought of as arrays of strings, so you can use square brackets on arrays,
var s = 'hello';
s[0] // "h"
s[1] // "e"
s[4] // "o"
Copy the code
2.3.2 Base64 transcoding
Sometimes text contains symbols that are not printable. Base64 is an encoding method where keyI converts any value into 64 printable characters: 0 to 9, A to Z, A to Z, +, and /. Js provides two base64-related methods,
- Btoa (): Converts any value to base64 encoding
- Atob (): base64 Converts bynum to the original value
let str = 'Hello Word';
btoa(string) // "SGVsbG8gV29ybGQh"
atob('SGVsbG8gV29ybGQh') // "Hello World!"
btoa('hello') / / an error
Copy the code
Note that these methods do not work with non-ASCII characters and will report errors. To convert non-ASCII characters into Base64 encoding, you must insert a transcoding link and use these two methods.
function b64Encode(str) {
return btoa(encodeURIComponent(str));
}
function b64Decode(str) {
return decodeURIComponent(atob(str));
}
b64Encode('hello') // "JUU0JUJEJUEwJUU1JUE1JUJE"
b64Decode('JUU0JUJEJUEwJUU1JUE1JUJE') // "Hello"
Copy the code
2.4 object
2.4.1 Object Reference
If different variable names refer to the same object, they are all references to that object, that is, to the same memory address. If you change one variable, it affects all the others
2.4.2 In operator
The IN operator is used to check whether an object contains a property, but it does not know whether the property is its own or inherited, so it needs to work with the object’s hasOwnProperty method.
var obj = {};
if ('toString' in obj) {
console.log(obj.hasOwnProperty('toString')) // false
}
Copy the code
2.4.3 for… In circulation
for… The in loop is used to iterate over all properties of an object. for… There are two usage considerations for the in loop.
- It iterates over all of the object’s enumerable properties and skips those that are not.
- It traverses not only the properties of the object itself, but also the inherited properties.
2.5 the function
2.5.1 Repeated declarations of functions
If the same function is declared more than once, the later declaration overrides the previous one. It is important to note that the previous declaration is invalid at any time due to the promotion of the function name.
function tyt(){
console.log(1)
}
tyt() / / 2
function tyt(){
console.log(2)}Copy the code
2.5.2 First-class citizen
JS treats a function as a value, with the same status as any other value (numeric value, string). Functions can be used wherever values can be used, they can be assigned to variables and object properties, they can be passed as arguments to other functions, or they can be returned as results.
2.5.3 Promotion of function names
var f = function () {
console.log('1');
}
function f() {
console.log('2');
}
f() / / 1
Copy the code
2.5.6 length attribute
The length property of the function returns the number of arguments that the function expects to pass in. The length property is distorted if the default value is set.
(function (a) {}).length / / 1
(function (a = 5) {}).length / / 0
(function (a, b, c = 5) {}).length / / 2
Copy the code
2.5.7 toString ()
For custom functions, calling the toString() method of the function returns the source code. For native functions, function (){[native code]} is returned.
2.5.8 Variable promotion inside the function
As with global scopes, “variable promotion” occurs within function scopes. A variable declared by the var command is promoted to the head of the function body no matter where it is located.
2.5.9 Scope of functions
The function itself is also a value and has its own scope. Its scope, like that of a variable, is the scope in which it is declared, regardless of the scope in which it is run.
let a = 1;
let x = test(){
console.log(a)
}
function test2(){
let a = 2;
x();
}
test2() / / 1
Copy the code
The scope in which a function executes is defined, not invoked.
2.5.10 Parameter Transfer Mode
If the argument is a primitive type value (numeric, string, Boolean), it is passed by value. That is, modifying parameter values inside the function body does not affect the outside of the function.
var p = 2;
function f(p) {
p = 3;
}
f(p);
p / / 2
Copy the code
In the above code, the variable p is a value of primitive type, and the function f is passed by value. So, inside the function, the value of p is a copy of the original value, and no matter how you change it, it doesn’t affect the original value.
If the function argument is a value of a compound type (array, object, other function), it is passed by reference. That is, the address of the original value passed to the function, so modifying arguments inside the function will affect the original value.
var obj = { p: 1 };
function f(o) {
o.p = 2;
}
f(obj);
obj.p / / 2
Copy the code
Note that if the function internally modifiers, instead of a property of the parameter object, the entire parameter is replaced, the original value is not affected.
var obj = [1.2.3];
function f(o) {
o = [2.3.4];
}
f(obj);
obj / / [1, 2, 3]
Copy the code
In the above code, inside the function f(), the argument object obj is replaced entirely with another value. This does not affect the original value. This is because the value of the formal argument (o) is actually the address of the argument obj, and reassigning to o causes o to point to another address. The value stored at the original address is of course not affected.
2.5.11 Closure
function f1() {
var n = 999;
function f2() {
console.log(n);
}
return f2;
}
var result = f1();
result(); / / 999
Copy the code
A closure is the function F2, a function that reads the internal variables of other functions. Since in the JavaScript language, only the child functions inside a function can read the internal variables, a closure can be understood simply as “a function defined inside a function.” The best thing about closures is that they can remember the context in which they were born. In essence, a closure is a bridge between the inside and outside of a function.
The main use of closures is to read variables inside the outer function, and to keep those variables in memory at all times. Closures allow the environment in which they were created to exist.
function createIncrementor(start) {
return function () {
return start++;
};
}
var inc = createIncrementor(5);
inc() / / 5
inc() / / 6
inc() / / 7
Copy the code
Closures are also useful for encapsulating the private properties and methods of an object. Each time the outer function is run, a new closure is generated, which in turn preserves the inner variables of the outer function, so memory consumption is high. Therefore, you should not abuse closures, which can cause performance problems for your web pages.
2.5.11 Expression of the function to be called immediately
According to JS syntax, parentheses () follow the function name to call the function. Sometimes, we need to call the function immediately after the function is defined. In this case, you should not enclose parentheses after the function definition, as this would cause a syntax error.
function(){ /* code */} ();// SyntaxError: Unexpected token
Copy the code
The reason for this error is that the function keyword can be used as either a statement or an expression.
/ / statements
function f() {}
/ / expression
var f = function f() {}
Copy the code
To avoid parsing ambiguity, JavaScript dictates that if the function keyword appears at the beginning of a line, it should be interpreted as a statement. Therefore, the engine sees the function keyword at the beginning of the line and thinks that this paragraph is all function definitions and should not end with parentheses, so it reports an error.
By extension, any method that allows the interpreter to process function definitions as expressions, such as the following three, will have the same effect.
var i = function(){ return 10; } ();true && function(){ /* code */} ();0.function(){ /* code */} (); !function () { /* code */} (); ~function () { /* code */} (); -function () { /* code */} (); +function () { /* code */} ();Copy the code
Normally, this “immediate function expression” is used only for anonymous functions. Its purpose is twofold: first, there is no need to name functions to avoid polluting global variables; Second, a separate scope is formed inside IIFE, which can encapsulate some private variables that cannot be read externally.
2.5 an array
2.5.1 length attribute
The length attribute is writable. If you artificially set a value less than the current number of members, the number of members in the array is automatically reduced to the value set by length.
var arr = [ 'a'.'b'.'c' ];
arr.length / / 3
arr.length = 2;
arr // ["a", "b"];
arr.length = 0;
arr / / []
Copy the code
An effective way to empty an array is to set the length property to 0.
2.5.2 Array vacancy
var a = [1.1];
a.length / / 3
a[1] // undefined
var b = ['a'];
b.length = 3;
b[1] // undefined
Copy the code
The length attribute does not filter for empty Spaces. If it is empty, use the array’s forEach method, for… The in structure and the object. keys method are traversed, and the empty space is skipped.
var a = [, , ,];
a.forEach(function (x, i) {
console.log(i + '. ' + x);
})
// No output is generated
for (var i in a) {
console.log(i);
}
// No output is generated
Object.keys(a)
/ / []
Copy the code