Learn how to handle errors

1.alert(‘ MOOCs ‘); => a semicolon is accidentally written in Chinese. Syntax: Uncaught SyntaxError: lnvalid or unexpected token Uncaught SyntaxError: an invalid or incorrect symbol

2.alert; Syntax: Uncaught ReferenceError: mooc is not defined Uncaught ReferenceError, mooc is not defined

2. Alret (‘ MOOC ‘); Syntax: Uncaught ReferenceError: Alert is not defined Uncaught ReferenceError, alert is not defined

Second, the variable

Basic knowledge of

Variables are symbolic variables that store values in memory, not values themselves. They are simply containers that store values

The default value of a variable is defined but not initialized. The default value is undefined. A variable is not initialized until it is defined by var and initialized

var a; console.log(a); //undefined var a=10; console.log(a); / / 10Copy the code

Common errors with variables 1. Assigning a value to a variable instead of the var definition will not raise an error, but will cause scope problems 2. Attempts to use a character that is neither defined by var nor assigned a value will result in a reference error console.log(b); //Reference Error

A valid variable name can contain only letters, digits, underscores (_), and ¥, but cannot start with a digit. 2. Cannot be a keyword or reserved keyword. 3. Case-sensitive, a and A are two different variables

Variable declaration enhancement

Variable declaration promotion: You can use a variable declared later in advance without raising an exception. When variable declaration promotion, only the definition of the variable is promoted, not its value

console.log(a);
var a=12; //undefined
Copy the code

Variable declaration promotion is a frequently asked interview question

Js basic data type

Two basic data types

Basic data type Number, null, Boolean, string, undefined in stack: after the data storage way is advanced. Complex data type object, Array, Function, the RegExp, Date, Map, Set, such as Symbol in the heap Through the use of a corresponding kept in a stack pointer for the values in the heap,

Data type details

number

It is not a number, but it is a value of numeric type typeof NaN; In fact, in mathematics, if the result is not a number, the result is NaN. NaN is a special value, it is not self-equiequal, it is the only non-reflexive value, NaN! =NaN results in true

IsNaN receives an argument and tries to convert it to a value. Any value that cannot be converted to a value returns true, so, A non-numeric value will also return true, and number. isNaN will first determine if the parameter passed is a Number, and if it is a Number, then determine if it is a NaN

Safe integer means that integers in this range can be converted to binary storage without loss of precision. The maximum range of integers that can be safely rendered is 2^53-1. MAX_SAFE_INTEGER in ES6 is defined as number.max_safe_INTEGER, the minimum integer number.min_safe_INTEGER If a calculation results in a value that exceeds the js value range, then this value is automatically converted to a special Infinity value. If one calculation returns a positive or negative Infinity value, that value cannot be included in the next calculation. Typeof Infinity; isInfinite; typeof Infinity; //number

Type string

Common methods for strings

methods function
charAt Gets the specified position character
subString Extract the substring
subStr Extract the substring
slice Extract the substring
toUpperCase Uppercase the string
toLowerCase Change the string to lowercase
indexOf Retrieve string

SubString (),subStr(),slice() subString(a,b) returns the subString ‘abcdefg’ from a to b (excluding b). SubString (3,5) //de if the second argument is omitted, Is extracted from the index to the end of the string, and argument A can be less than b

SubStr (a,b) will yield a substring of length b starting from a ‘abcdefg’. SubStr (3,2); //de a can also be negative to indicate the reciprocal position

The slice(a,b) method yields a substring starting at A and ending at b (excluding b). The value of parameter A can be negative and parameter A must be less than b

The indexOf() method returns the first occurrence of a specified string, or -1 if the string to be indexed is not present

Object Typeof NULL; // The object interview is easier to test

Conversion of data types

Use the number() function

Interview question–> Conversion rules for other values to numeric values

Strings -> numbers Pure character strings can become numbers, strings that are not pure numbers will become NaN Boolean values -> the number true becomes 1, False to 0 undefined and null-> numeral undefined to NaN,null to 0 Symbol type cannot be converted to numeral, error will be reported. Objects (including arrays) are first cast to the corresponding primitive type value, and if a non-numeric primitive type value is returned, it is then cast to a number following the above rules. In order to convert a value to the corresponding primitive type value, the abstract operation ToPrimitive first checks (through the internal operation Defaultvalue) whether the value has a valueof() method. If a primitive type value is present and returned, that value is used for the cast. If not, the return value of toString() is used (if present) for the cast. If neither Valueof () nor toString() returns a base type value, TypeError is generated.

Use the parseInt() function

The parselnt() function converts a string to an integer parseInt(‘3.14’); ParseInt (‘3.14 is PI ‘); // 3 All text will be truncated parseInt(‘ PI is 3.14’); // NaN If the string does not start with a number, convert to NaN parseInt(‘3.99’); // 3 Parselnt () is not rounded

Use the parseFloat() function

The parselnt() function converts a string to a floating point number, similar to the point parseInt notices

String () method

Conversion rules for other values to string values

Number -> string becomes the same string, scientific notation and other base numbers are converted to base 10 and all other data types are converted to the same string null and undefined, Null is converted to “null” and undefined to “undefined” symbol is converted directly, but only explicit casts are allowed. Using implicit casts will cause errors

Expressions and operators

Arithmetic operator

Implicit type conversion If the operand involved in a mathematical operation is not numeric, then JS will automatically convert the operand to numeric. The essence of the food conversion is to call the Number*() function internally

When performing decimals, the toFixed () method of the number is called to preserve the specified number of decimal places

The ~ operator returns the complement of 2 and converts the number to a 32-bit integer, so we can invert it with ~. ~x is roughly equivalent to – (x+1).

When is the + operator used to concatenate strings if an operand is a string or can be converted to a string by the following steps? If one of the operands is an object (including an array), the ToPrimitive abstract operation is called on it first, which in turn calls [[Defaultvalue]], with the number as the context. If it cannot be converted to a string, it is converted to a numeric type for evaluation. To put it simply, if one of the operands of + is a string (or if the above steps result in a string), string concatenation is performed, otherwise number addition is performed. So for operators other than addition, as long as one side is a number, the other side is converted to a number.

Power operation math.h pow (2, 3); //8 Math.sqrt(81); / / 9

Round up math.ceil (2.4); Math.floor(2.4); / / 2

The difference between null and undefined 1. They both belong to basic data types. Undefined means undefined and NULL means empty object 2. Undefined is returned when it is declared but not defined. Null is used to assign to variables that may return objects. 3.null==undefined; //true null===undefined//false

(1) Equality comparison between a string and a number, after converting a string to a number. (2) Equality comparison between other types and Boolean types. Boolean values are converted to numbers before other rules apply. (3) Equality comparison between null and undefined, the result is true. All other values compared to them return false values. (4) Equality comparison between objects and non-objects, objects call ToPrimitive abstract operation first, then compare. (5) Equality comparison returns false if an operation has a NaN value (NaN itself is not equal to NaN). (6) If both operation values are objects, then compare whether they refer to the same object. The equality operator returns true if both operands refer to the same object, false otherwise.

Unequal and incongruent! = means unequal; ! == means not congruent 5! =6 //true 5! ==6 //true 5! =’5′ //false 5! ==’5′ //true

The priority of a logical operation is not -> and -> or

Integrated operations the operation order of the operations – > math – > relationship operations – > logic operations logic operation && 8 / / 2 2 2 | | / / 8 August

Interview questions

Internal properties[[Class]]What is the

All objects (such as arrays) whose Typeof returns’ object ‘contain an internal attribute [[Class]] (we can think of this as an internal classification, rather than a Class in the traditional sense). This property cannot be accessed directly, usually by the Object. The prototype. ToString (…). To view, for example:

Object. The prototype. ToString. Call ([1, 2, 3]); //'[object Array]'Copy the code

Describes the built-in objects in Js

The built-in object in JS mainly refers to some global value properties, functions and constructors used to instantiate other objects that exist in the global scope before the program is executed. In general, we often use the global variable value NaN, undefined, global functions such as parseInt(), parseFloat() used to instantiate object constructors such as Date, object, etc., and provide mathematical calculation of the single built-in objects such as Math object.

The difference between Undefined and undeclared

A variable declared in a scope but not yet assigned is undefined. In contrast, variables that have not been declared in scope are undeclared. ReferenceError: b is not defined However, we can use Typeof’s security precautions to avoid errors because Typeof returns “undefined” for undeclared(or not defined) variables.

How do I get a safe undefined value

Because _undefined is an identifier, it can be used and assigned as a variable, but this will affect the normal judgment of undefined. The expression void__ returns no value, so undefined is returned. Void does not change the result of the expression; it just makes the expression return no value. By convention we use void 0 to get undefined.

Write the basic specification of JavaScript

  1. A function scope of all variable declarations should be mentioned function first, use a var statement, not allowed two consecutive var statement, stating if the variable has no value, should give the initial value of the variable assignment of the corresponding type, facilitate others when reading code, can be clear at a glance know variables corresponding to the types of values.
  2. You need constants to replace strings such as address and time in your code.
  3. Use ‘===’, ‘whenever possible when making comparisons. ==’ instead of ‘==’, ‘! = ‘.
  4. Do not add methods to the prototype of built-in objects, such as Array,Date.
  5. The switch statement must have a default branch.
  6. For loops and if statements must use braces.

Flow control statement

If statement

Daffodil number: the number of units, tens, hundreds to the third power is equal to itself

Var n = Number(prompt(' please enter a three-digit Number ')); // Verify the value entered by the user if (! IsNaN (n) &&100 <= n &&n <= 999) {var a = math.floor (n / 100); // ten var b = math.floor (n / 10) % 10; Var c = n % 10; If (math.pow (a, 3) + math.pow (b, 3) + math.pow (c, 3) == n) {alert(' this number is daffodils '); } else {alert(' This number is not daffodils '); }} else {// Enter invalid alert(' the number you entered is invalid '); }Copy the code

String method

Var n_str = n.tostring (); var a = Number(n_str.charAt(2)); var b = Number(n_str.charAt(1)); var c = Number(n_str.charAt(0));Copy the code

The for loop

The while loop

Break and continue statements, do while loops

Break terminates the loop immediately. It can only be used in loop statements. It can be used in both for and while loops

for(var i=0; i<10; i++){ console.log(i); if(i==4){ break; } / / 0,1,2,3,4Copy the code

Break is used in a while statement, usually with while(true){}

var n=1;
while(true){
  if(n*n>456789){
      console.log(n);
      break;
    }
    n++;
 }
Copy the code

“Continue” is used to skip an iteration of the loop and continue with the next iteration of the loop. Do while is a post-test loop statement. The do-while loop writes the condition at the end of the loop so that the body must execute at least once before checking whether the condition is true. Determines whether to continue executing the body of the loop.

Do *{loop body}while(loop execution condition)Copy the code

Random number function

Math.random() returns the integer parseInt(math.random ()*(b-a+1)+a in the interval [a,b]

An array of

Subscript out of bounds js specifies that access to items that do not exist in an array will return undefined without error

Var array=[‘A’,’B’,’C’] var array=new array (‘A’,’B’,’C’) var array=new array (4)

2. Array.isarray () can be used to detect arrays

Array methods

Array header and tail operations

methods function
push() Insert a new item at the tail
pop() Delete at the tail
unshift() Insert a new item in the header
shift() Delete in the header

Push () method

1. Push () is used to push a new item to the end of the array. The argument is the item 2 to be pushed. 3. The array changes immediately after the push() method is called. No assignment is required

Pop () method

In contrast to push(), pop() removes the last item in the array. 2. Pop () not only removes the last item in the array, but also returns the deleted item

Unshift () method

1. The unshift() method is used to insert a new item in the header of the array. The parameter is the item to insert. 3. The array changes immediately after the unshift() method is called. No assignment is required to return the array length

The shift () method

In contrast to unshift((), the shift() method used to remove items with subscript 0 from an array returns the deleted value

Splice () method

The splice() method replaces the specified item in the array

var arr =['A', 'B', 'c', 'D', 'E', 'F','G']; arr.splice(3 , 2 , 'x', 'Y' , 'z'); // Replace two consecutive console.log(arr) entries starting with subscript 3; // [' A', 'B', 'c', 'x', 'Y', 'z', 'F', 'G']Copy the code

Slice () method

The slice() method is used to get subarrays, similar to the slice() method of strings. 2. Slice (a,b) intercepts subarrays starting with subscripts a and ending with subscripts B (but excluding subscripts B). 3

Join () and split() methods

The join() method of an array converts an array to a string. The split() method of a string converts a string to an array

Concat (), reverse(), indexOf(), includes()

The reverse() method is used to place all the items in the array in order. The reverse() method searches for the elements in the array and returns the element in which it is located. If the element does not exist, The -1 includes() method checks whether an array contains a specified value and returns a Boolean value

Base type values and reference type values

For example, When var a=b is passed When you compare with ==
Base type value Numeric, string, Boolean, etc A new copy is generated in memory Compares whether the values are equal
Reference type value Objects, arrays Instead of creating a new copy in memory, a new variable points to the same object Compares whether memory addresses are the same, that is, whether they are the same object

The interview questions

How the Array constructor behaves when it has only one parameter value

When the Array constructor takes only one numeric argument, that argument is used as the default length of the Array, rather than as an element in the Array. This creates an empty array with its length property set to the specified value. Constructor Array(..) The new keyword is not required. If not, it will be automatically replaced.

{} and[]What are the results of valueOf and toString for?

  • ValueOf of {} is {}, and toString is"[object object]"
  • []The result of valueOf is[]ToString results in “”

What is a false value object?

In certain cases, browsers create their own exotic values based on normal JavaScript syntax. These are “false value objects.” False value objects look like normal objects (they all have attributes, etc.), but the most common example of casting them to a Boolean that yields false is document.all, which is an array-like object that contains all the elements on a page, The DOM(not the JavaScript engine) is provided for use by JavaScript programs.

What does the ~ operator do?

~ returns the complement of 2, and ~ converts the number to a 32-bit integer, so we can use ~ for rounding. ~x is roughly the same thing as – x+1.

Parsing a number in a string and converting a string cast to a number both return numbers. What’s the difference between them?

Parsing allows non-numeric characters in strings (such as parseInt()) in left-to-right order, stopping if non-numeric characters are encountered. Conversions (such as Number ()) do not allow non-numeric characters, or they fail and return NaN.

Common regular expressions

  • Match the hexadecimal color value var regex = / # ([O – a – fA – 9 F] {6} | [O – a – fA – 9 F] {3})/g;
  • Match date, such as yyyy – mm – dd format var regex = / ^ [0-9] {4} – (8 [1-9] | [0-2] 1) – (0 [1-9] | [12] [0-9] [01] | 3) $/;
  • Var regex = /^[1-9][0-9]{4,10}$/g; l/
  • Var regex =/^1[34578]\d{9}$/g;
  • User name regular var regex = / ^ [a zA – Z $] [a zA – ZO – _ $9] 16th {4} $/;

How to implement random array sort

  1. Sort the array elements randomly using the array sort method. Math.random() compares the number with 0.5, and returns 1 if it is greater than 0.5, -1 if it is less than 0.5, and does not swap.
Function randomSort(a, b) {return Math. Random () > 0.5? 1:1; }Copy the code

Disadvantages: The location where each element is sent to the new array is not random, because the sort() method is compared sequentially. 2. Randomly extract an element from the original array and add it to the new array

function randomSort( arr) { var result = []; while ( arr.length > 0){ var randomIndex = Math.floor( Math.random() *arr.length); result.push( arr[randomIndex]); Arr. Splice (randomIndex, 1); } return result; }Copy the code
  1. Swap the elements of an array randomly (similar shuffle algorithm)
Function randomSort( arr) { var index , randomIndex, temp, len = arr.length; for (index = 0; index < len; index++) { randomIndex = Math.floor(Math.random()* ( len - index)) + index; temp = arr[index] ; arr[index] = arr[ randomIndex]; arr[randomIndex] = temp ;Copy the code

function

Definition of a function

  • Functions encapsulate statements that make code easy to reuse
  • Functions have the advantage of being ‘defined once, called many times’
  • Using functions, you can simplify your code and make it readable

Like variables, functions must be defined before they can be used; Use the function keyword to define functions

Function call

  • Executing all statements in the function body is called calling a function
  • To call a function, simply write a pair of parentheses after the function name

Order of function execution

  • Define the function, the function will not be executed
  • Functions must wait until called and can be called multiple times

Enhancement of function declarations

Function declarations can be promoted; But if the function is defined in the form of an expression, there is no lifting property

fun(); Var fun=function(){}Copy the code

Priority promotion of functions

Functions are promoted first, followed by variable declarations

fun(); Var fun=function(){alert('A')} function fun(){alert('B')} fun(); var fun(){alert('B')} fun(); / / the pop-up ACopy the code

Function declaration promotion and variable declaration promotion should be more classic interview questions

The parameters and return values of the function

Function add(a,b){var sum=a+b; console.log(sum); } add(3,5) // pass in arguments when calling the functionCopy the code

The case where the number of parameters and arguments is different

Argument > parameter, no parameter receives its argument < argument, and the output value is undefined

function add(a,b,c){ var sum=a+b+c; console.log(sum); / / NaN} the add (3, 5)Copy the code

arguments

  • Arguments inside a function denotes the list of arguments it receives, which is an array-like object
  • Array-like objects: All attributes are a sequence of natural numbers starting at 0 and have a length attribute, similar to arrays. You can use square brackets to write subscripts to access an attribute value of an object, but cannot call array methods
Function fun(){var sum=0; function fun(){var sum=0; for(var i=0; i<arguments.length; i++){ sum+=arguments[i]; }} to the console. The log (sum) fun (,44,66 33)Copy the code

The return value

The return value of a function can be received by a variable

function fun(a,b){ return a+b; } var result = fun (3, 5);Copy the code

Calling a function that returns a value can be treated as a normal value, and thus can appear anywhere a value can be written.

When a function is called, it immediately exits the function as soon as a return statement is encountered, returning execution rights to the caller

function fun() {
  console.log( 'A');
  return 'B' ;
  console.log( 'C');
}
console.log(1);
var char = fun();
console.log(char);
console.log(2);
// 1 A B 2
Copy the code

So when you write an if statement, you don’t have to do an else branch

Function oushu(a){if(a%2==0) return true; return false; }Copy the code

The sort() method is built into javascript

Var arr = [5, 6, and 41,9,22,33]; arr.sort(function(a,b){ return b-a; }) console. The log (arr) / / [41,33,22,9,6,5]Copy the code

recursive

An internal statement of a function can call the function itself, thus initiating an iteration of the function. In a new iteration, statements that call the function itself are executed, resulting in another iteration. When a function is executed once, no new iterations are made, and the function is returned layer by layer, recursively.

Elements of recursion

Boundary conditions: Determine when a recursion terminates, also known as recursive exit recursion patterns: How does a big problem break down into smaller problems, also known as recursive bodies

Recursively take the factorial

// Write a function that calls itself internally to form recursion. Function factorial(n) {// Factorial (n! It's n times n minus 1 factorial. ?? If (n == 1) return 1; if (n == 1) return 1; // Return n * (n-1)! return n * factorial(n - 1); } var result = factorial(6); alert(result);Copy the code

Recursive algorithm: Fibonacci sequence

Recursive algorithm: deep copy

See another article for these two algorithms (Algorithms javascript-1/2)

Global and local variables

Variable scoped JS is a functional scoped programming language in which variables have meaning only within the function in which they are defined

Global variables do not define variables inside any function

Shadowing effect If a function defines a variable with the same name as the global variable, the variables inside the function will mask the global variable

var a=5; function fun(){ a++; var a=10; console.log(a); //10 } fun(); console.log(a); / / 5Copy the code

Var a=10 = NaN = NaN = NaN = NaN = NaN = NaN = NaN = NaN

Parameters are also local variables

var a=10; function fun(a){ a++; console.log(a); //8 } fun(7); console.log(a); / / 10Copy the code

The scope chain

In function nesting (where a function can define another function within it), a variable looks for its definition layer by layer from the inside out

var a = 10; var b = 20; function fun() { var c = 30; function inner() { var a = 40; var d = 50; console.log(a, b, c, d); / / 40,20,30,50} inner (); } fun();Copy the code

Global variables are defined without var

  • The global variable is defined when the variable is first assigned, if var is not added
Function fun(){// the letter c is not called with the var keyword, so it becomes the global variable c=3; c++; } fun(); // Outside of the function is console.log(c), which accesses the variable C; / / 4Copy the code

closure

Js functions generate closures. Closures are a combination of the function itself and the state of the environment in which the function is declared

Functions can remember the context in which they were defined, even if the function is not called in the environment in which it is defined, it can access the variables of the environment in which it is defined.

Observe closures

  • A closure is created each time a function is created;
  • However, closure features often require the function to be executed “somewhere else” to be observed.

Closures are useful because they allow us to associate data with functions that operate on that data, which bears a slight resemblance to object-oriented programming.

Closure functionality: memorization, simulation of private variables

Closure purpose 1 – Memorability When a closure is created, the state of the function’s environment is always kept in memory and is not automatically cleared after the outer function is called. That’s the memorability of closures.

CreateCheckTemp (standardTemp) {function checkTemp(n) {if (n <= standardTemp) {alert(' your temperature is normal '); } else {alert(' Your temperature is too high '); } } return checkTemp; Var checkTemp_A = createCheckTemp(37.1); var checkTemp_A = createCheckTemp(37.1); Var checkTemp_B = createCheckTemp(37.3); var checkTemp_B = createCheckTemp(37.3); CheckTemp_A (37.2);Copy the code

Closure purpose 2 – Simulate private variable title: define a variable a, the requirement is guaranteed that this a can only be specified operations (such as add 1, multiply 2), but not other operations, how to program? Use closures at this point

Function fun() {// Define a local variable a var a = 0; return { getA: function () { return a; }, add: function () { a++; }, pow: function () { a *= 2; }}; } var obj = fun(); // If you want to use a outside of fun, the only way is to call the getA() method console.log(obj.geta ()); Obj.add (); // we want to increment a by 1. console.log(obj.getA());Copy the code

Considerations for using closures

  • Do not abuse closures as they can cause performance problems for your web pages and, in severe cases, memory leaks. A memory leak is when the dynamically allocated memory in a program is not released or cannot be released for some reason.

A memory leak is when the dynamically allocated memory in a program is not released or cannot be released for some reason.

Execute the function IIFE immediately

IIFE (Immediately Invoked Function Expression) is a special JavaScript Function writing method. Once defined, the Function Expression is Invoked Immediately.

(function(){ statements })(); //function (); The function of the last pair of parentheses is to run the functionCopy the code

The role of IIFE

  1. Assign a value to a variable
var age = 42; Var sex = 'female '; Var title = (function () {if (age < 18) {return 'kid '; } else {if (sex == 'male ') {return' male '; } else {return 'lady '; }}}) (); alert(title); ` `Copy the code
  1. Convert global variables to local variables
var arr=[]; for(var i=0; i<5; i++){ (function(i){ arr.push(function(){ alert(i) }); })(i) } arr[2]();Copy the code