Expressions and statements
Expression: 1 + 3 statement (Statements end with a semicolon. A semicolon indicates the end of a statement. Multiple statements can be written on a single line. Var a = 1 + 3; Empty statement:;
Variable promotion andundefined
If a variable is declared without an assignment, the value of the variable is undefined. Undefined is a JavaScript keyword that means “undefined”.
var a;
a // undefined
Copy the code
Variable promotion only applies to variables declared with the var command. If a variable is not declared with the var command, no variable promotion occurs.
block
JavaScript uses curly braces to group multiple related statements together, called blocks. Unlike most programming languages, JavaScript blocks do not constitute separate scopes. That is, variables in a block belong to the same scope as variables outside the block.
{ var a = 1; }
a // 1
Copy the code
The above code declares and assigns variable A inside the block, and then outside the block, variable A is still valid. This shows that the block does not constitute a separate scope, and is no different than if the block were not used. As a result, blocks used alone make little sense in JavaScript and are rarely seen. Blocks are often used to form other more complex syntactic structures, such as for, if, while, function, etc.
Judge the statement attention points
Switch statement If all cases do not match, the last part of default is executed. Note that each case block must contain as many break statements as possible, otherwise it will execute the next case block instead of breaking out of the switch structure. Inside the switch statement is the strict equality operator.
Looping statements
While loop, for loop, do… The while loop
Data type *
- Number: integers and decimals (e.g.1 and 3.14)
- String: Text composed of characters (e.g. “Hello World”)
- Boolean:
true
And (true)false
(false) Two specific values undefined
: indicates undefined or does not exist, that is, there is no value here because there is no definitionnull
: indicates that there is no value, that is, the value is the state of “none”.Symbol
: Type value- Object: A collection of values
An object can be divided into three subtypes.
- Object in a narrow sense
- Array
- Functions
Determine the data type
JavaScript has three ways to determine what type a value is.
typeof
The operatorinstanceof
The operatorObject.prototype.toString
methods
The typeof operator
- Numeric, string, and Boolean values are returned respectively
number
,string
,boolean
. - The function returns
function
. undefined
returnundefined
.- Otherwise, all other cases return
object
.
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
Copy the code
Typeof displays both arrays and objects as objects, so how to distinguish them? The instanceof operator does this.
Null and undefined, both of which are automatically converted to false in if statements, and the equality operator (==) even reports that they are equal. Currently null and undefined are basically synonymous with each other, with some subtle differences. Null is special in that JavaScript includes it within the object type. This is not to say that null datatypes are objects, but rather a convention from early deployments of JavaScript that wasn’t quite right, and was later modified when it was too late to break existing code, so it’s stuck.
null
Represents a null value, i.e. the value there is now null. When a function is called, a parameter is passed without any valuenull
. For example, a function may take an error thrown by the engine as an argument, which is passed in if nothing goes wrong during executionnull
Is displayed, indicating that no error occurs.undefined
Represents “undefined”, and returns belowundefined
Typical scenario.
// The variable is declared but not assigned var I; Function f(x) {return x; function f(x) {return x; } f() // undefined // Object has no assigned attribute var o = new Object(); O.p // undefined // undefined function f() {} f() // undefinedCopy the code
Boolean value
The conversion rule is that all values are considered true except for the following six values that are converted to false.
undefined
null
false
0
NaN
""
or' '
(Empty string)
The numerical
why
0.1 + 0.2 = = = 0.3 / / false / 2.9999999999999996/0.3/0.1 (0.3 0.2) = = = (0.2 0.1) / / falseCopy the code
For a computer, two numbers are added in binary form and converted to decimal when the result is rendered. The 0.1 RPM binary infinite loop, beyond the precise range of JS, only saves 52 bits after the mantras, and there is a round-off error.
Decimal fraction is converted to binary the decimal calculation: in 2 decimal fraction, can get the product, the product of the integer part, and in 2 by the rest of the decimal part, and get a product, and then remove the integer part of the product, and so on, until all the decimal portion is zero, the product at this time for the last of the binary 0 or 1. Or achieve the required accuracy.
For example: 0.7= (0.1 0110 0110...) 0.7 * 2 = 1.4 B = = = = = = = = remove the integer part 1 0.4 * 2 = 0.8 = = = = = = = = remove the integer part 0 0.8 * 2 = 1.6 = = = = = = = = remove the integer part 1 0.6 * 2 = 1.2 = = = = = = = = remove the integer part 1 0.2 * 2 = 0.4 = = = = = = = = remove the integer part 0 0.4 * 2 = 0.8 = = = = = = = = remove the integer part 0 0.8 * 2 = 1.6 = = = = = = = = remove the integer part 1 0.6 * 2 = 1.2 = = = = = = = = remove the integer part 1 0.2*2=0.4======== Take integer part 0 // 0.1 to binary 0.0 0011 0011 0011 0011... (0011 infinite loop) // 0.2 to binary 0.0011 0011 0011 0011 0011 0011... (0011 Infinite loop)Copy the code
Binary decimal conversion to decimal calculation: mainly multiplied by 2 to the minus power, starting from the decimal point, multiplied by 2 to the minus one power, 2 to the minus two power, 2 to the minus three power and so on.
//0.001 converted to decimal 0*1/2 0*1/4 1*1/8 so 0.125Copy the code
Scientific notation:
123e3 // 123000
123e-3 // 0.123
Copy the code
NaN is a special JavaScript value that stands for “Not a Number,” mostly when parsing a string to a Number fails.
5 - 'x' // NaN Typeof NaN // 'number' // 'isNaN' methods can be used to determine if a value is' NaN '. isNaN(NaN) // trueCopy the code
IsNaN also returns true for objects and arrays.
IsNaN ({}) / / true / / equivalent isNaN (Number ({})) / / true isNaN () [' xzy '] / / true / / equivalent isNaN (Number ([' xzy '])) / / trueCopy the code
However, isNaN returns false for empty arrays and arrays with only one numeric member.
IsNaN ([]) / / false [] 0 isNaN ([123]) / / false [123] 123 isNaN ((' 123 ')) / / false/' 123 ', 123Copy the code
The above code returns false because these arrays can be converted to numeric values by the Number function, as described in the Data Type Conversion section.
Therefore, it is a good idea to determine the data type before using isNaN.
function myIsNaN(value) {
return typeof value === 'number' && isNaN(value);
}
Copy the code
A more reliable way to determine NaN is to take advantage of the fact that NaN is the only value in JavaScript that is not equal to itself.
function myIsNaN(value) { return value ! == value; }Copy the code
The parseInt method is used to convert a string to an integer. The parseFloat method is used to convert a string to a floating point number.
Notes on strings
Base64 is an encoding method that can turn any character into a printable character. This encoding method is not used for encryption, but to avoid special characters and simplify the process of the program.
JavaScript natively provides two Base64 related methods.
- Btoa () : Converts string or binary values to Base64 encoding
- Atob () : Base64 encoding is converted to the original encoding
To convert non-ASCII characters into Base64 encoding, you must insert a transcoding link and use these two methods. Because these methods do not work with non-ASCII characters, an error will be reported.
function b64Encode(str) { return btoa(encodeURIComponent(str)); } function b64Decode(str) { return decodeURIComponent(atob(str)); } b64Encode(' hello ') // "juu0jujeewjuu1jue1juje" b64Decode(' juu0jujeewjuu1jue1juje ') // "hello"Copy the code
object
All keys of the object are strings, so you can use them with or without quotes. However, if the key name does not meet the criteria for identifying a name (such as the first character being a number, or containing a space or operator) and is not a number, it must be quoted or an error will be reported.
The assignment point and square bracket operators of attributes can be used not only to read values, but also to assign values.
o.p = 'abc';
o['p'] = 'abc';
Copy the code
To view all the properties of an Object itself, use the object.keys method. The delete command is used to delete an attribute of an object.
The delete command returns false in only one case, if the property exists and cannot be deleted.
var o = Object.defineProperty({}, 'p', {
value: 123,
configurable: false
});
o.p // 123
delete o.p // false
Copy the code
In the above code, the p attribute of the o object cannot be deleted, so delete returns false.
Also, note that the delete command can only delete properties of the object itself, not inherited properties.
var o = {};
delete o.toString // true
o.toString // function toString() { [native code] }
Copy the code
In the above code, toString is an inherited property of object O. Although the delete command returns true, the property is not deleted and still exists.
Finally, the delete command cannot delete variables declared by the var command, only attributes.
for… The in loop is used to iterate over all properties of an object.
Here is an example of using for… In loop, an example of extracting object properties.
var obj = {
x: 1,
y: 2
};
var props = [];
var i = 0;
for (props[i++] in obj);
props // ['x', 'y']
Copy the code
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.
An array of
Essentially, an array is a special kind of object. The Typeof operator returns an array of type Object. The object. keys method returns all the key names of the array.
The length property of an array, which returns the number of members of the array.
var arr = ['a', 'b']; arr.length // 2 arr[2] = 'c'; arr.length // 3 arr[9] = 'd'; arr.length // 10 arr[1000] = 'e'; Arr. Length // 1001 a[2.1] = 'ABC '; a.length // 0Copy the code
The code above shows that the array’s numeric keys do not need to be consecutive, and the value of the length attribute is always 1 greater than the largest integer key.
Setting the array keys to string and decimal, respectively, does not affect the length attribute. Because the value of the length attribute is equal to the largest number key plus 1, and this array has no integer key, the length attribute remains 0. If the array’s key name is to add an out-of-range value, the key name is automatically converted to a string.
In JavaScript, some objects are called “array-like objects.” That is, they look like arrays and you can use the length property, but they’re not arrays, so you can’t use some array methods. Here is an array-like object.
var obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
Copy the code
The operator in, which checks for the presence of a key name, applies to objects as well as arrays.
var arr = [ 'a', 'b', 'c' ];
2 in arr // true
'2' in arr // true
4 in arr // false
Copy the code
for… An in loop can iterate not only over objects but also over groups of numbers, since arrays are just a special kind of object.
However, for… In traverses not only all numeric keys in the array, but also non-numeric keys.
var a = [1, 2, 3];
a.foo = true;
for (var key in a) {
console.log(key);
}
// 0
// 1
// 2
// foo
Copy the code
The code above also iterates over the non-integer key foo as it iterates over the number array. Therefore, it is not recommended to use for… In traverses the number group. Consider a for loop or a while loop for array traversal.
The forEach method for arrays can also be used to iterate over arrays
Using the delete command to delete an array member creates a void and does not affect the length attribute.
There’s a difference between an array where a position is empty and an array where a position is undefined. 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); } for (var I in a) {console.log(I); } // do not generate any output object.keys (a) // []Copy the code
If a position is undefined, it will not be skipped when traversing.
function
Declaration of functions
- (1) function command
- (2) Function expression
- (3) Function constructor – not recommended
If you declare the same function using both the function command and an assignment statement, you always end up using the assignment statement definition.
var add = new Function( 'x', 'y', 'return x + y' ); Function add(x, y) {return x + y; }Copy the code
The repeated declaration of a function. if the same function is declared more than once, the subsequent declaration overwrites the previous declaration.
The JavaScript language treats a function as a value, with the same status as any other value (numeric, string, Boolean, and so on). Where values can be used, functions can be used. For example, functions can be assigned to variables and attributes of objects, passed as arguments to other functions, or returned as the result of functions. A function is just a value that can be executed, there is nothing special about it.
Functions are called first-class citizens in the JavaScript language because they are on an equal footing with other data types.
JavaScript engines treat function names as if they were variable names, so when you declare a function with the function command, the entire function is promoted to the header of the code just like the variable declaration.
Properties and methods of a function
name
Property returns immediately afterfunction
The name of the function after the keyword.length
Property returns the number of arguments that the function expects to pass, that is, the number of arguments in the function definition.- Function of the
toString
Method returns the source of the function.
Scope refers to the scope within which a variable exists. Javascript has only two types of scope: a global scope, where variables exist throughout the program and can be read anywhere; The other is function scope, where variables exist only inside a function.
The scope of the function itself
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, independent of the scope in which it is run.
var a = 1;
var x = function () {
console.log(a);
};
function f() {
var a = 2;
x();
}
f() // 1
Copy the code
In the above code, function X is declared outside of function F, so its scope is bound outside. The inner variable A is not evaluated inside function F, so it prints 1 instead of 2.
In short, the scope in which a function executes is the scope in which it was defined, not the scope in which it was called.
It is easy to make A mistake if function A calls function B without considering that function B does not refer to the internal variables of function A.
var x = function () {
console.log(a);
};
function y(f) {
var a = 2;
f();
}
y(x)
// ReferenceError: a is not defined
Copy the code
The above code takes function x as an argument and passes in function y. However, function x is declared outside of function y, so the internal variable A of function Y cannot be found, resulting in an error.
Parameter elision. Function parameters are not required. Javascript allows parameter elision. The value of the omitted parameter becomes undefined. Note that the length attribute of the function has nothing to do with the actual number of arguments passed in, but only the expected number of arguments passed in. However, there is no way to omit only the front arguments and keep the back ones. If you must omit the first argument, only pass undefined explicitly.
You can set default values for the parameters of a function by using the following method.
function f(a){
a = a || 1;
return a;
}
f('') // 1
f(0) // 1
Copy the code
The code above | | “or operation,” said that if a value, it returns a, otherwise returns the predetermined default value (1).
This notation performs a Boolean operation on a and returns a only if true. However, in addition to undefined, Boolean values for 0, null, null, and so on are false. That is, in the above function, you cannot have a equal to 0 or an empty string, otherwise the default value will be returned even if there are arguments.
To avoid this problem, use the following more precise notation.
function f(a) { (a ! == undefined && a ! == null) ? a = a : a = 1; return a; } f() // 1 f('') // "" f(0) // 0Copy the code
In the above code, the argument to f is null or 0, which does not trigger the default value of the argument.
delivery
Function parameters that are primitives (numeric, string, Boolean) are passed by passes by value. This means that changing parameter values inside the function 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.
However, if the function argument is a value of a compound type (array, object, other function), the pass 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
In the above code, f is passed the address of the argument object obj. Therefore, modifying the property P of obj inside the function affects the original value.
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 function f, the argument object obj is replaced entirely with another value. This does not affect the original value. This is because there is an assignment relationship between the formal parameter (o) and the actual parameter obj.
// function f inside o = obj;Copy the code
In the code above, changes to O are reflected in OBj. However, assigning a new value to O severs the connection between O and OBj, so that subsequent changes do not affect OBj.
In some cases, if you want to get the effect of addressing a variable of a primitive type, you can write it as a property of a global object.
var a = 1;
function f(p) {
window[p] = 2;
}
f('a');
a // 2
Copy the code
In the above code, variable A is originally passed by value, but is written as a property of the window object, which achieves the effect of address passing.
If there is an argument with the same name, the value that appears last is taken.
The arguments object contains all arguments to the function run time, arguments[0] being the first argument, arguments[1] being the second, and so on. This object can only be used inside the function body.
Note that arguments is an object, although it looks a lot like an array. Array-specific methods, such as slice and forEach, cannot be used directly on arguments objects.
However, you can make arguments use array methods by passing arguments in with the Apply method.
/ / method is used to apply myfunction. Apply (obj, the arguments). / / use a merger with another Array Array. The prototype. Concat. Apply ([1, 2, 3], the arguments)Copy the code
To make arguments objects use array methods, the real workaround is to convert Arguments to a real array. Here are two common conversion methods: slice and filling in new arrays one by one.
var args = Array.prototype.slice.call(arguments);
// or
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
Copy the code
Closures are simply understood as “functions defined inside a function.” The best thing about a closure is that it can “remember” the environment in which it was created. For example, F2 remembers the environment in which it was created, F1, so f2 can be used to get the internal variables of F1. In essence, a closure is a bridge between the inside and outside of a function.
A closure is useful for reading variables inside a function and for keeping those variables in memory at all times. In the example below, closures cause internal variables to remember the result of the last call.
function createIncrementor(start) {
return function () {
return start++;
};
}
var inc = createIncrementor(5);
inc() // 5
inc() // 6
inc() // 7
Copy the code
Note that 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.
Function expressions called immediately (IIFE)
In Javascript, a pair of parentheses () is an operator that follows a function name to indicate that the function is called. For example, print() calls the print function. Sometimes we need to call a function immediately after it is defined. In this case, you should not enclose parentheses after the function definition, as this would cause a syntax error. The reason for this error is that the function keyword can be used as either a statement or an expression.
The solution is to keep function out of the beginning of the line and have the engine interpret it as an expression. The easiest way to do this is to put it in parentheses.
(function(){ /* code */ }()); Function (){/* code */})();Copy the code
In both cases, the engine will assume that it is followed by a representation, not a function definition statement, so it avoids errors. This is called the immediate-Invoked Function Expression, or IIFE.
The eval command executes a string as a statement.
eval('var a = 1; '); a // 1Copy the code
The operator
Comparison operators can compare values of all types, not just numeric values.
In addition to the equality operator symbol and the exact equality operator, the algorithms for the other comparison operators are as follows.
- If both operators are strings, they are compared in lexicographical order (actually comparing Unicode code points).
- Otherwise, convert both operators to numeric values and compare (equivalent to calling first
Number
Function).
The following example is a comparison between values of two primitive types.
5 > '4' // true // equivalent to 5 > Number('4') // equivalent to 5 > 4Copy the code
If the operator is an object, it must first be converted to a valueOf its primitive type by calling the valueOf method, and then the toString method if it returns an object.
var x = [2]; X > / / true / / '11' is equivalent to [2]. The valueOf (), toString () > / / '11' is' 2 '>' 11 'Copy the code
Strings are compared in lexicographical order. The JavaScript engine internally compares the Unicode code point for the first character, if equal, the Unicode code point for the second character, and so on.
NaN is not equal to any value (including itself). Plus 0 is minus 0.
When the data of two compound types (object, array, function) is compared, it is not to see if their values are equal, but to see if they refer to the same object.
{} === {} // false
[] === [] // false
(function (){} === function (){}) // false
Copy the code
Undefined and null are strictly equal to themselves.
undefined === undefined // true
null === null // true
Copy the code