introductory

Identifiers: All identifiers in JS that we can name ourselves can be called identifiers

  • Variable names, function names, and attribute names are all identifiers
  • When naming an identifier, follow the following rules:
  • The identifier can contain letters, digits, underscores (_), and $(C)
  • Identifiers cannot start with a number
  • The identifier cannot be a key or reserved word in ES
  • Identifiers are generally hump nomenclature
  • The first letter of each word is capitalized and the rest of the letters are lowercase
  • JS is actually using Unicode encoding when storing identifiers.
  • So in theory, all utF-8 contents can be used as identifiers
  • Direct quantity: The value of the data directly used by the program

The data type

JavaScript has six primitive (immutable) data types:

  • Boolean Indicates the Boolean type

  • An Array is a set of sequential collections, each value of which is called an element. JavaScript arrays can contain any data type. In JavaScript, an array is essentially an object that starts at 0;

  • Number JavaScript does not distinguish between integer and floating point numbers, and uses Number to represent the Number type (number.max_value….) MIN…. Infinity/small)

  • String String type (toString() or “+” can convert other types to strings)

  • Object reference type

  • Functio () Function type

  • Undefined (1. Declare variable but not assign value 2. Operate variable directly, variable is not declared and not defined 3. 4. Function does not return a value. Default return undefined;)

  • Typefo () to obtain a variable’s value of the data type string, number, Boolean, object, undefined, the function;

  • Objects JavaScript objects are an unordered set of key-values

System transformation

Non-numeric to numeric: NaN is returned if it cannot be turned

  • NullNull pointer derived from undefined(essentially a special object, indicating that the object is empty or has no object)
  • NaN: not a number Specifies the type of a number.Nan is returned for all nan involved Is not equal to any value including and itself
  • The isNAN method is used to determine (if it is not a number, it will try to convert to a number);
  • number()
  • ParseInt () operates on the beginning of a number;
  • parseFloat()

ToString string conversion

  • The toString method returns a copy
  • The String() function can be converted to any typestring

Boolean Boolean conversion

  • 0,””,null,undefined turn bool false all other true
var person = {
    name: 'Bob'.age: 20.tags: ['js'.'web'.'mobile'].city: 'Beijing'.hasCar: true.zipcode: null
};
Copy the code
  • The keys of JavaScript objects are strings, and the values can be any data type. The person object defines a total of six key-value pairs,
  • Each key is called an attribute of the object, for example, the Person name attribute is ‘Bob’ and the Zipcode attribute is null.
  • To get the properties of an object, we use object variables. The way the attribute name works:
person.name; // 'Bob'
person.zipcode; // null
Copy the code

variable

  • Separate multiple variables with ‘,’;
  • Var or let declaration
  • Variables can be not only numbers, but also any data type.
  • A variable is represented by a variable name. The variable name is a combination of uppercase and lowercase letters, digits, $, and underscores, and cannot start with a digit.
  • Variable names cannot also be JavaScript keywords, such as if, while, etc. Declare a variable with the var statement, as in:
var a; // the value of a is undefined
var $b = 1; $b = 1; $b = 1
var s_007 = '007'; // s_007 is a string
var Answer = true; // Answer is a Boolean value true
var t = null; // t is null
Copy the code
  • Variable names can also be in Chinese, but don’t get yourself into trouble.
  • In JavaScript, variables are assigned with the equal sign =. Any data type can be assigned to a variable, the same variable can be assigned repeatedly,
  • It can be a variable of different types, but only once. For example:
var a = 123; The value of a is the integer 123
a = 'ABC'; // A becomes a string
Copy the code
  • Languages in which the variable itself is of variable type are called dynamic languages, as opposed to static languages. Static languages must specify the type of a variable when defining it, and an error will be reported if the assignment does not match the type.
  • For example, if Java is a static language, the assignment statement is as follows:
int a = 123; // a is an integer variable declared as an int
a = "ABC"; // Error: cannot assign strings to integer variables
Copy the code
  • This is why dynamic languages are more flexible than static languages.
  • Do not equate an assignment statement with a mathematical equals sign:
var x = 10;
x = x + 2;
Copy the code

String()

Returns the character at the specified position

  • The charAt() method returns a character at a specified position
  • The returned character is a string of length 1
stringObject.charAt(index)
Copy the code
  1. The subscript of the first character in the string is 0. The subscript of the last character is the string length minus one (string.length-1).
  2. If the index argument is not between 0 and String.length-1, the method returns an empty string

Returns the first occurrence of the specified string

  • The indexOf() method returns the first occurrence of a specified string value in a string.
  • This method retrieves the string stringObject from beginning to end to see if it contains substring.
  • Optional argument to look for substring starting at startpos on stringObject, or starting at stringObject if this argument is not present.
  • If a substring is found, return the location of the first occurrence of the substring
  • The character position starts at 0.
stringObject.indexOf(substring, startpos)
Copy the code
  1. The indexOf() method is case sensitive.
  2. If the string value to retrieve is not present, the method returns -1.

String split()

  • The split() method splits a string into an array of strings and returns this array.
stringObject.split(separator,limit)
Copy the code

Extract the string substring()

  • The substring() method is used to extract the character of a string intermediate between two specified subscripts
stringObject.substring(startPos,stopPos) 
Copy the code
  1. All characters from start (including the start position) to stop-1 are returned, and the length is stop minus start.
  2. If the arguments start and stop are equal, the method returns an empty string (that is, a string of length 0).
  3. If start is larger than stop, the method swaps these two arguments before extracting the substring

Extract the specified number of characters substr()

  • The substr() method extracts a specified number of strings from the string starting at startPos. Grammar:
stringObject.substr(startPos,length)
Copy the code
  • The position from the end of the string if the parameter startPos is negative.
  • -1 is the last character in the string, -2 is the second-to-last character, and so on.
  • If startPos is negative and the absolute value is greater than the string length, startPos is 0.

Multiline string

  • Because multiline strings are too cumbersome to write with \n, the latest ES6 standard adds a new way to represent multiline strings, using backquotes.Said:

Template string

  • To concatenate multiple strings, use the + sign to concatenate:
Var name = 'c '; var age = 20; Var message = 'hello ',' name ', 'age' '; alert(message);Copy the code
  • Multivariable connection, the + sign is more troublesome. A template string has been added to ES6The ${}The representation is the same as the multi-line string above, but it will automatically replace the variables in the string:
var name = 'Ming';
var age = 20;
var message = Hi, `${name}This year, you${age}Years old! `;
alert(message);
Copy the code
  • It is important to note that strings are immutable, so if you assign to an index of the string, there is no error, but there is no effect either

  • JavaScript provides some common methods for strings. Note that calling these methods does not change the contents of the original string itself, but returns a new string:

ToUpperCase () capitalizes all strings; ToLowerCase () all lowercase; IndexOf () searches for the position of the specified string; Return without finding- 1; Substring () returns the string of the specified index interval; (`var s = 'hello, world' s.substring(0, 5); // from index 0 to 5 (excluding 5), return 'hello' s.substring(7); // From index 7 to end, return 'world')
Copy the code

Math()

  • Round up ceil() rounds up
  • Floor is rounded down
  • Round round
  • The random number

Array()

  • An array object is a collection of objects that can be of different types. Each member object of an array has a “subscript” to indicate its position in the array, which is the method defined by the array from zero:
  1. Defines an empty array:
varArray name =new Array(a);Copy the code
  1. Define an array with n empty elements:
varArray name =new Array(n);
Copy the code

When defining an array, initialize the data directly:

Var array name = [< element 1>, < element 2>, < element 3>... ;Copy the code
  • Array elements use:
Array name [subscript] = value;Copy the code
  • Array subscripts are enclosed in square brackets, starting at 0.

Array methods

  • . Length specifies a new value, which causes the Array size to change.
  • An Array can be indexed to change the corresponding element to a new value, so assigning an index to an Array directly changes the Array
  • Most other programming languages do not allow you to change the size of an array directly, and out-of-bounds access to the index will result in an error.
  • JavaScript Array doesn’t have any errors. When writing code, it is not recommended to change the Array size directly. When accessing an index, ensure that the index does not overstep the bounds

The arguments array class

  • The length attribute of arguments refers to the number of arguments;
  • The length of the function refers to the number of parameters;

indexOf

withStringA similar,ArrayIndexOf () can also be used to search for the position of a specified element:var arr = [10.20.'30'.'xyz'];
arr.indexOf(10); // Element 10 has an index of 0
arr.indexOf(20); Element 20 has an index of 1
arr.indexOf(30); // Element 30 was not found, return -1
arr.indexOf('30'); // Element '30' has an index of 2
Copy the code

slice()

Slice () correspondsStringSubstring (), which interceptsArrayAnd return a new oneArray:var arr = ['A'.'B'.'C'.'D'.'E'.'F'.'G'];
arr.slice(0.3); ['A', 'B', 'C'] ['A', 'B', 'C']
arr.slice(3); // From index 3 to end: ['D', 'E', 'F', 'G']
Copy the code
  • Notice that the start and stop parameters for slice() include the start index, not the end index
  • If no arguments are passed to slice(), it intercepts all elements from beginning to end.

Push and pop

  • Push () adds elements to the end of the Array, and pop() removes the last element of the Array:

Unshift and shift

  • If you want to add elements to the Array header, use the unshift() method, which removes the first element of the Array

sort()

  • You can sort the current Array, which will directly modify the current Array element position. When called directly, the default order is sorted. 1, 0 is equal;

The reverse () inversion

splice()

  • The splice() method is a “universal method” for modifying an Array. It removes elements starting at the specified index and then adds elements from that location:
var arr = ['Microsoft'.'Apple'.'Yahoo'.'AOL'.'Excite'.'Oracle'];
// Remove 3 elements from index 2, then add 2 more elements:
arr.splice(2.3.'Google'.'Facebook'); // Return the deleted element ['Yahoo', 'AOL', 'Excite']
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
// Delete:
arr.splice(2.2); // ['Google', 'Facebook']

arr; // ['Microsoft', 'Apple', 'Oracle']
// Add, do not delete:
arr.splice(2.0.'Google'.'Facebook'); // Return [], because no elements have been deleted
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
Copy the code
  • Concat () concatenates two arrays and returns a new array;
var arr = ['A'.'B'.'C'];
var added = arr.concat([1.2.3]);
added; // ['A', 'B', 'C', 1, 2, 3]
arr; // ['A', 'B', 'C']
Copy the code
  • Note that the concat() method does not modify the current Array. Instead, it returns a new Array. In fact, the concat() method can accept any element and Array, automatically unpack the Array, and add them all to the new Array

join()

  • The join() method is a very useful method that concatenates each element of the current Array with the specified string and returns the concatenated string:
  • If an Array element is not a string, it is automatically converted to a string and then concatenated.

object

  • Object properties: reflect some specific properties of the object, such as the length of the string, the length and width of the image, etc.
  • Methods of objects: Actions that can be performed on objects;
  • JavaScript provides several inline objects, such as String, Date, Array, etc., which are defined before using an object.
  var objectName =new Array(a);// Use the new keyword to define objectsorvarobjectName =[]; Syntax for accessing object properties: objectName.propertyNameCopy the code
  • Methods for accessing objects:
objectName.methodName()
Copy the code
  • JavaScript uses a {… } represents an object, and the key-value pairs are declared in the form XXX: XXX, separated by,. Note that the last key-value pair does not need to be appended at the end, and some browsers (such as earlier versions of Internet Explorer) will report an error if it is appended.
  • Access to properties is through. Operator, but this requires that the attribute name be a valid variable name. If the attribute name contains special characters, it must be enclosed in ” :
var xiaohong = {
    name: 'little red'.'middle-school': 'No.1 Middle School'
};
Copy the code
  • Xiaohong’s property name, middle-school, is not a valid variable, so it needs to be enclosed in “. Access to this property is also unavailable. Operator, which must be accessed with [‘ XXX ‘] :
xiaohong['middle-school']; // 'No.1 Middle School'
xiaohong['name']; // '/'
xiaohong.name; // '/'
Copy the code
  • All attributes of a JavaScript object are strings, but the values corresponding to the attributes can be of any data type.
  • What is returned if a nonexistent property is accessed? JavaScript states that accessing nonexistent properties does not report an error, but returnsundefined:
  • JavaScript objects are dynamically typed, and you are free to add or remove attributes to an object:
var xiaoming = {
    name: 'Ming'
};
xiaoming.age; // undefined
xiaoming.age = 18; // Add an age attribute
xiaoming.age; / / 18
delete xiaoming.age; // Delete the age attribute
xiaoming.age; // undefined
delete xiaoming['name']; // Delete the name attribute
xiaoming.name; // undefined
delete xiaoming.school; // Delete a school attribute that does not exist
Copy the code
  • If we want to check whether Xiaoming has a property, we can use theinOperator:
var xiaoming = {
    name: 'Ming'.birth: 1990.school: 'No.1 Middle School'.height: 1.70.weight: 65.score: null
};
'name' in xiaoming; // true
'grade' in xiaoming; // false
Copy the code
  • Be careful, though; if in determines that a property exists, it doesn’t have to be Xiaoming’s; it might be inherited by Xiaoming

  • HasOwnProperty () can be used to determine whether a property is own or inherited:

Var xiaoming = {name: 'xiaoming'}; xiaoming.hasOwnProperty('name'); // true xiaoming.hasOwnProperty('toString'); // falseCopy the code

If (){}

  • JavaScript treats null, undefined, 0, NaN, and the empty string “” as false, and all other values as true.

cycle

  • forThe most common place for loops is to use an index to iterate over a set of numbers, suitable for knowing the number of loops;
  • The while loopAs long as the condition is true, the cycle is always suitable for the unknown;
  • The continue statementImmediately terminate the loop, return to the head of the loop structure, and start the next loop,
  • The tag labelThe statement is preceded by a label, equivalent to a locator, used to jump to any point in the program; (Out of a code block, out of a particular loop)
  • All three conditions of the for loop can be omitted. If there is no judgment condition to exit the loop, the break statement must be used to exit the loop, otherwise the loop is dead.
  • End the loop and start the next loop
var x = 0; for (;;) {// loop indefinitely if (x > 100) {break; } x ++; }Copy the code
  • for ... inA variant of the for loop isfor ... inLoop, which loops through all the properties of an object in turn
var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    console.log(key); // 'name', 'age', 'city'
}
Copy the code
  • To filter out inherited attributes of an object, use hasOwnProperty() :
var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key); // 'name', 'age', 'city'
    }
}  
Copy the code
  • Since Array is also an object, and the index of each of its elements is treated as an attribute of the object, for… The in loop loops through the Array index directly
var a = ['A', 'B', 'C'];
for (var i in a) {
    console.log(i); // '0', '1', '2'
    console.log(a[i]); // 'A', 'B', 'C'
}
Copy the code
  • The while loop has only one judgment condition. If the condition is satisfied, the loop will continue. If the condition is not satisfied, the loop will exit.
Var x = 0; var n = 99; while (n > 0) { x = x + n; n = n- 2; } x; / / 2500Copy the code
  • The final loop isdo{... }while()The only difference between a loop and a while loop is that the condition is judged not at the beginning of each loop, but at the end of each loop:
var n = 0; do { n = n + 1; } while (n < 100); n; / / 100Copy the code
  • withdo { ... } while()Be careful with loops; loops execute at least once, while for and while loops may not execute at all.

The operator

  • Ternary operator: if condition is true, execute 1, otherwise execute code 2

  • And operations: the first true returns the last value; The first false returns the first operator

  • As long as there is a NAN,null,undefinde returns NAN….

  • Or operation: returns the first true, and the last if all false

  • Non-operation: Return Boolean regardless of type

Map and Set

Map

var m = t.map (function () {item,index,array
	return item +2;
})
console.log(m);
console.log(t);
Copy the code
  • Is a set of pairs of structures, with extremely fast lookup speed;
  • If the Map implementation, only need a “name” – “score” comparison table, directly according to the name of the search results, no matter how large the table, the search speed will not be slower.
  • Write a Map in JavaScript as follows:
var m = new Map([['Michael'.95], ['Bob'.75], ['Tracy'.85]]);
m.get('Michael'); / / 95
Copy the code
  • Initializing a Map requires either a two-dimensional array or an empty Map.
  • Map has the following methods:
var m = new Map(); // empty Map m.sat ('Adam', 67); // add a new key-value m.set('Bob', 59); m.has('Adam'); // if there is key 'Adam': true m.et ('Adam'); // 67 m.delete('Adam'); // delete key 'Adam' m.net ('Adam'); // undefinedCopy the code
  • A key corresponds to only one value. If you add a value to a key multiple times, subsequent values will overwrite previous values

Set

  • A Set, like a Map, is a Set of keys but does not store values. There is no duplicate key in Set because the key cannot be repeated
  • To create a Set, either supply an Array as input or create an empty Set
var s1 = new Set(a);/ / null Set
var s2 = new Set([1.2.3]); // contains 1, 2, 3
Copy the code
  • Duplicate elements are automatically filtered in Set
var s = new Set([1, 2, 3, 3, '3']);
s; // Set {1, 2, 3, "3"}
Copy the code
  • Note that the number 3 and the string ‘3’ are different elements

  • We can add elements to a Set using the add(key) method, which can be added repeatedly but has no effect:

s.add(4); s; // Set {1, 2, 3, 4} s.add(4); s; Set {1, 2, 3, 4}Copy the code
  • The delete(key) method deletes elements:
var s = new Set([1, 2, 3]); s; // Set {1, 2, 3} s.delete(3); s; / / the Set {1, 2}Copy the code

可迭代

  • An Array can be traversed with a subscript loop, whereas maps and sets cannot be traversed with subscripts
  • To unify collection types, the ES6 standard introduces a new iterable type. Array, Map, and Set are all iterable types
  • Collections with iterable types are available through the new for… Of loops over
  • withfor ... ofLoop over the collection as follows
var a = ['A', 'B', 'C']; var s = new Set(['A', 'B', 'C']); var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]); For (var x of a) {// Array console.log(x); } for (var x of s) {// Set console.log(x); (var x of m)} for {/ / traverse Map the console. The log (x [0] + '=' + x [1]).Copy the code

for… Of loops and for… What’s the difference in the in loop?

  • for … The in loop, due to a historical legacy, iterates over the property names of the object. An Array Array is actually an object whose index of each element is treated as a property
  • When we manually add additional properties to the Array object, for… The in loop will have unexpected unintended effects
var a = ['A', 'B', 'C'];
a.name = 'Hello';
for (var x in a) {
    console.log(x); // '0', '1', '2', 'name'
}
Copy the code
  • for … The IN loop will include the name, but not the length property of the Array
  • for … The of loop fixes these problems completely by only iterating through the elements of the collection itself
var a = ['A'.'B'.'C'];
a.name = 'Hello';
for (var x of a) {
    console.log(x); // 'A', 'B', 'C'
}
Copy the code
  • Directly use iterable’s built-inforEachMethod, which receives a function that is automatically called back on each iteration
'use strict';
var a = ['A'.'B'.'C'];
a.forEach(function (item, index, array) {
    // item: refers to the value of the current element
    / / index, index
    // array: points to the array object itself
    console.log(item + ', index = ' + index);
});

//foreEach returns undefind
Copy the code
  • Set is similar to Array, but Set has no index, so the first two arguments to the callback function are the elements themselves
var s = new Set(['A'.'B'.'C']);
s.forEach(function (element, sameElement, set) {
    console.log(element);
});
Copy the code
  • The Map callback takes value, key, and Map itself:
var m = new Map([[1.'x'], [2.'y'], [3.'z']]);
m.forEach(function (value, key, map) {
    console.log(value);
});
Copy the code
  • If you are not interested in certain parameters, you can ignore them because JavaScript function calls do not require that the parameters be consistent
  • For example, just get the element of the Array:
var a = ['A'.'B'.'C'];
a.forEach(function (element) {
    console.log(element);
});
Copy the code

Data types and reference types

  • Reference types on the heap: function object object array array
  • Basic types on the stack (string, number, Boolean, null, and undefined)
  • The reference type changes every time, because it refers to an address

function

The difference between passing a function argument by reference and passing a value:

  • If the parameter of a function is of a simple type, a numeric copy of the value type is made and passed inside the function.
  • If it is a reference type, the address of the reference type is copied to the parameter passed to the function.

Function definition and call

  • Function indicates that this is a function definition;

  • Abs is the name of the function;

  • (x) Lists the parameters of the function in parentheses, separated by,.

  • {… } is the body of a function, which can contain several statements, or none at all

  • Note that when a statement inside a function body is executed, once it reaches a return, the function completes execution and returns the result. Therefore, very complex logic can be implemented inside functions through conditional judgments and loops.

  • If there is no return statement, the function will return undefined after execution.

  • A JavaScript function is also an object. The abs() function defined above is actually a function object, and the function name abs can be treated as a variable pointing to that function.

  • The second way to define a function is as follows:

var abs = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return-x; }};Copy the code
  • In this wayfunction (x) { ... }Is an anonymous function that has no function name. However, this anonymous function is assigned to the variable ABS, so it can be called from the variable ABS.
  • Both definitions are completely equivalent, but note that the second way is syntactically complete by adding one at the end of the function body;Indicates the end of the assignment statement.
  • JavaScript allows you to pass in any number of arguments without affecting the call, so it’s ok to pass in more arguments than you define, even though you don’t need them internally
  • There is no problem passing in fewer parameters than defined
abs(); // the abs(x) function will receive undefined, the calculation result is NaN.Copy the code
  • To avoid receiving undefined, check the parameters
function abs(x) {
    if (typeofx ! = ='number') {
        throw 'Not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return-x; }}Copy the code

Message dialog box

  • Document.write () input content;
  • JavaScript- Alert message dialog
  • JavaScript- Confirm message dialog
confirm(str); STR: Return value of the text to display in the message dialog box:BooleanValue Return value: when the user clicks"Sure"Button when returntrueWhen the user clicks"Cancel"Button when returnfalseNote: What button can be determined by the return valueCopy the code
  • Prompt displays a message dialog box, which is usually used to ask for information that you need to interact with the user
prompt(str1, str2); Str1: To display the text in the message dialog box, cannot be modified STR2: the content in the text box can be modified: - Click the OK button, the content in the text box will be returned as the function value - click the Cancel button, will be returnednull
Copy the code
  • The open() method finds an existing or newly created browser window.
window.open([URL], [window name], [Parameter string]) URL: This parameter is optional. The URL or path of the web page is displayed in the window. If this parameter is omitted, or if its value is an empty string, the window does not display any documents. Window name: Indicates the name of the open window. This parameter is optional.1.The name consists of letters, digits, and underscore characters.2."_top","_blank","_self"A name with special meaning. _blank: displays the target page in a new window. _self: displays the target page in the current window. _top: displays the target page in the upper window3.Only one window with the same name can be created. To create multiple Windows, the name must be different4.Name cannot contain Spaces. String: Optional. Set window parameters separated by commas.Copy the code
  • Close () closes the window
Usage:window.close();   // Close this windowOr < window object >.close();// Close the specified window
Copy the code

arguments

  • Arguments, which only takes effect inside a function and always refers to all arguments passed in by the caller of the current function
  • Gets a parameter, similar to an array access method
function foo(x) {
    console.log('x = ' + x); // 10
    for (var i=0; i
        console.log('arg ' + i + ' = ' + arguments[i]); // 10, 20, 30
    }
}
foo(10, 20, 30);
Copy the code
  • With arguments, you can get all the arguments passed by the caller, even if the function doesn’t define any arguments:
function abs() {
    if (arguments.length === 0) {
        return 0;
    }
    var x = arguments[0];
    return x >= 0 ? x :-x;
}

abs(); / / 0
abs(10); / / 10
abs(9 -); / / 9
Copy the code
  • In fact, arguments is most commonly used to determine the number of arguments passed in. You might see something like this:
// foo(a[, b], c)
B is an optional parameter. If only two parameters are sent, b is null by default:
function foo(a, b, c) {
    if (arguments.length === 2) {
        // The actual parameters are a and B, and c is undefined
        c = b; // Assign b to c
        b = null; // b changes to the default value
    }
    // ...
}

Copy the code
  • To change the middle argument b to “optional”, you can only use arguments, then resize the argument and assign the value.

Variable scope and destruct assignment

  • If a variable is declared inside the function body, the scope of the variable is the whole function body and the variable cannot be referenced outside the function body
  • Variables of the same name in different functions are independent and do not affect each other
  • JavaScript functions can be nested; internal functions can access variables defined by external functions, and vice versa
  • JavaScript functions start looking for variables from their own function definition and work “inside” out. If the inner function defines a variable with the same name as the outer function, the variables of the inner function are “masked” by the variables of the outer function.

Global variables, namespaces

  • Global variables are bound to Windows, and different JavaScript files that use the same global variable or define top-level functions with the same name can cause naming conflicts and be difficult to detect.
  • One way to reduce collisions is to bind all of your variables and functions into a global variable;
  • Putting all your code into a unique namespace, MYAPP, greatly reduces the possibility of global variable collisions

Local scope

  • Let instead of var declares a block-scoped variable;

constant

  • The ES6 standard introduces a new keyword const to define constants. Const and LET both have block-level scope

methods

  • To bind a function to an object, called a method of that object
// Write an age() method to return the age of xiaoming:
var xiaoming = {
    name: 'Ming'.birth: 1990.age: function () {
        var y = new Date().getFullYear();
        return y- this.birth; }}; xiaoming.age;// function xiaoming.age()
xiaoming.age(); // This year the call is 25, next year it will be 26
Copy the code
  • A function bound to an object is called a method, and it is no different from a normal function, but it uses the this keyword internally

  • Inside a method, this is a special variable that always points to the current object, which is the variable xiaoming

  • This. birth gets the birth attribute in Xiaoming

  • Let’s break it down:

function getAge() {
    var y = new Date().getFullYear();
    return y- this.birth;
}

var xiaoming = {
    name: 'Ming'.birth: 1990.age: getAge
};

xiaoming.age(); // 25, normal result
getAge(); // NaN
Copy the code
  • If called as an object method, such as xiaoming.age(), the function’s this points to the object being called, which is xiaoming, as we would expect.

  • If you call a function alone, such as getAge(), the function’s this points to the global object, which is the window.

  • Even worse, if you write it like this:

var fn = xiaoming.age; // get the age function fn() for xiaoming; // NaNCopy the code
  • No! To make sure this points correctly, you must call it as obj.xxx()!

  • Since this is a huge design error, it will not be easy to correct.

  • ECMA decides to make the function’s this point to undefined in strict mode, so in Strict mode you get an error:

'use strict';

var xiaoming = {
    name: 'Ming'.birth: 1990.age: function () {
        var y = new Date().getFullYear();
        return y- this.birth; }};var fn = xiaoming.age;
fn(); // Uncaught TypeError: Cannot read property 'birth' of undefined
Copy the code
  • This decision just exposes the error in time, but does not solve the problem of where this should point to.

  • Sometimes, you refactor a method like this:

'use strict';

var xiaoming = {
    name: 'Ming'.birth: 1990.age: function () {
        function getAgeFromBirth() {
            var y = new Date().getFullYear();
            return y- this.birth;
        }
        returngetAgeFromBirth(); }}; xiaoming.age();// Uncaught TypeError: Cannot read property 'birth' of undefined
Copy the code
  • It was wrong again! This pointer only points to xiaoming in the age function. This also points to undefined in the age function. (In non-strict mode, it repoints to the global object Window!)

  • We can fix this by first capturing this with a that variable:

'use strict';

var xiaoming = {
    name: 'Ming'.birth: 1990.age: function () {
        var that = this;		// Start by capturing this inside the method
        function getAgeFromBirth() {
            var y = new Date().getFullYear();
            return y- that.birth;		// Use that instead of this
        }
        returngetAgeFromBirth(); }}; xiaoming.age();/ / 25
Copy the code
  • withvar that = this, you can safely define other functions inside a method, instead of piling everything into a single method

apply()

  • To specify which object the function’s this refers to, use the apply method of the function itself
  • The first argument is the this variable that needs to be bound
  • The second argument, Array, represents the argument to the function itself
// Use apply to fix getAge() :
function getAge() {
    var y = new Date().getFullYear();
    return y- this.birth;
}

var xiaoming = {
    name: 'Ming'.birth: 1990.age: getAge
};

xiaoming.age(); / / 25
getAge.apply(xiaoming, []);		// 25, this points to xiaoming, and the parameter is null
Copy the code

call()

  • Another method similar to apply() is call(), with the only difference:
  • Apply () packs the parameters into an Array and passes them in;
  • Call () passes the arguments in order.
  • For example, call math.max (3, 5, 4) using apply() and call() respectively:
Math.max.apply(null[3.5.4]); / / 5
Math.max.call(null.3.5.4); / / 5
Copy the code
  • For normal function calls, we usually bind this to NULL

A decorator

  • You can change the behavior of a function dynamically with apply()
  • All objects in JavaScript are dynamic, and even built-in functions can be redirected to new ones.
// If you want to count how many times parseInt() is called, you can find all the calls and manually add count += 1; // The best solution is to replace the default parseInt() with our own function: 'use strict'; var count = 0; var oldParseInt = parseInt; Window.parseint = function () {count += 1; return oldParseInt.apply(null, arguments); // call the function}; // Test: parseInt('10'); parseInt('20'); parseInt('30'); console.log('count = ' + count); / / 3Copy the code

Higher-order functions

  • Functions actually refer to a variable, and since variables can refer to functions and parameters of functions can accept variables, a function can accept another function as an argument, and this kind of function is called a higher-order function.
  • To write a higher-order function is to make its arguments accept other functions
  • Simple higher-order functions:
function add(x, y, f) {
    return f(x) + f(y);
}
Copy the code

map/reduce

  • Since the map() method is defined in JavaScript Array, we call Array’s map() method, passing in our own function, and get a new Array as a result:
'use strict';
function pow(x) {
    return x * x;
}
var arr = [1.2.3.4.5.6.7.8.9];
var results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);
Copy the code
  • Note: Map () takes pow, the function object itself
  • Map (), being a higher-order function, actually abstracts the rules so that we can compute not only simple f(x)=x2, but also arbitrarily complex functions, such as converting all Array numbers to strings:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.map(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']
Copy the code

raduc

  • Array reduce() applies a function to Array [x1, x2,x3…]. On,
  • This function must take two arguments
  • Reduce () continues the cumulative calculation with the next element of the sequence, and the result is:
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
Copy the code
  • For example, summing an Array can be done using reduce
var arr = [1.3.5.7.9];
arr.reduce(function (x, y) { 
    return x + y;
}); / / 25
Copy the code

filter

  • It is used to filter out certain elements of an Array and return the remaining elements.
  • Array’s filter() also receives a function.
  • Unlike map(), filter() applies the passed function to each element in turn,
  • It then decides whether to keep or discard the element based on whether the return value is true or false.

So in an Array, we delete the even numbers, we keep the odd numbers, we could write it like this

var arr = [1, 2, 4, 5, 6, 9, 10, 15]; var r = arr.filter(function (x) { return x % 2 ! = = 0; }); r; // [1, 5, 9, 15]Copy the code

To delete an empty string from an Array, write:

var arr = ['A', '', 'B', null, undefined, 'C', ' ']; var r = arr.filter(function (s) { return s && s.trim(); // Note: Versions below IE9 do not have the trim() method}); r; // ['A', 'B', 'C']Copy the code

The callback function

  • Filter () receives a callback function that can take multiple arguments. Usually we just use the first parameter, which represents an element of the Array. The callback can also take two additional arguments, representing the position of the element and the array itself;
var arr = ['A', 'B', 'C']; var r = arr.filter(function (element, index, self) { console.log(element); // Print 'A', 'B', 'C' console.log(index); // Print 0, 1, 2 console.log(self); // self is the variable arr return true; });Copy the code
- Filter can be used to subtly remove duplicate elements from Array: 'use strict'; var r, arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry']; r = arr.filter(function (element, index, self) { return self.indexOf(element) === index; }); console.log(r.toString()); // Removing duplicate elements depends on the fact that indexOf always returns the position of the first element. Subsequent duplicate elements are not equal to the position returned by indexOf and are therefore filtered out by filter.Copy the code

sort

  • For two elements x and y, return -1 if x is considered < y, 0 if x == y, and 1 if x > y
  • Minus 1 is the front one,1 is the back one;

closure

Function as the return value

  • In addition to accepting functions as arguments, higher-order functions can also return functions as result values.
  • One thing to keep in mind when returning closures is that the return function should not reference any loop variables, or variables that will change later

What if you must reference a loop variable? The method is to create another function that binds the current value of the loop variable with its arguments. The values that are bound to the function remain unchanged, regardless of subsequent changes to the loop variable:

function count() { var arr = []; for (var i=1; i<=3; i++) { arr.push((function (n) { return function () { return n * n; } })(i)); } return arr; } var results = count(); var f1 = results[0]; var f2 = results[1]; var f3 = results[2]; f1(); // 1 f2(); // 4 f3(); / / 9Copy the code

generator

  • Generator differs from function in that generator consists of functionDefinition (note the extraIn addition to the return statement, you can use yield to return multiple times.

Built-in objects

Encapsulate objects that can be called directly

Array

  • The index starts from zero
  • Create a new Array ()
  • (n) can be numeric, representing the length of the array
  • Array. length Gets the array length
  • Array methods are: push(),pop(),unshift(),shift()
  • Array to string: join() returns string;
  • Array reverse: Reverse () returns an array
  • Sort sort:return a-b
  • Concat concatenates two or more arrays and returns arrays
  • Slice (stard,end) intercepts the array from start to end-1 and returns the array
  • Splice (index,count) delete, insert, replace; Returns an array of deleted elements
  • IndexOf(searchValue,startIndex),lastIndexOf(

String

  • CharAt (index) The character itself to obtain
  • CharCodeAt (index) Indicates the character code of the index position
  • IndexOf (“) searches the given string from the string, returns the string position, returns -1 if fN is not found
  • Contrary lastindexOf (“);
  • Slice (stard,end) similarly, intercepts a segment
  • If the substring argument is negative, it is automatically converted to 0. Automatically smaller is the starting number
  • Substr (start,len) The total number of truncated strings. If start is negative, the negative value is added to the length of the string. If len is negative, the empty string is returned.
  • Split (separator) splits a string into an Array of strings, returning Array (separator: must, separator)
var date= '2016/05/05'; Var dataArr date.split("/") // Separated by special symbols in parenthesesCopy the code
  • Replace (regexp,replacement) returns a new String without modifying the original String (the first parameter, who you want to replace, what the second parameter is replaced with)
  • ToUpperCase () String in all uppercase
  • ToLowerCase () all lowercase

Standard object

  • Gets the typeof the object with the typeof operator, which always returns a string
  • Number, String, Boolean, function, and undefined differ from other types. Note that null is of type object, Array is of type object,
  • If we use typeof, we cannot distinguish null, Array, and object in the usual sense

Packaging object

  • The wrapper object is created with new,
  • Wrapped objects look and display exactly the same as their original values, but their type has changed to Object! So, comparing the wrapped object with the original value with === returns false
- Do not usenew Number(),new Boolean(),new String() Create a wrapper object; - useparseInt() orparseFloat() to convert any type to number; - useString() to convert any type toString, or to call an object's toString() method directly; - There is usually no need to convert any type to Boolean, because you can write directlyif(myVar) {... }; -typeofOperators can determine number, Boolean, string,functionandundefined; Judge -ArrayIn order to useArray.isArray(arr); Judge -nullPlease use themyVar= = =null; - Determines whether a global variable existstypeof window.myVar= = = 'undefined'; - Determines whether a variable exists inside a functiontypeof myVar= = = 'undefined'. Finally, some careful students pointed out that any object hastoString() How?nullandundefinedThere is no! That's true, except for these two special values, althoughnullAnd pretending to beobjectType. The more careful students point out,numberThe objecttoString() toSyntaxError: - 123.toString(); // SyntaxErrorIn this case, special treatment is required: -123..toString(); // '123', notice two dots! - (123).toString(); / / '123'Copy the code

Date

In JavaScript, the Date object is used to represent the Date and time.

To obtain the current system time, the time of the local operating system, use:var now = new Date(a);Copy the code
  • If you want to create a Date object with a specified Date and time, you can use:
var d = new Date(2015.5.19.20.15.30.123);
d; // Fri Jun 19 2015 20:15:30 GMT+0800 (CST)
Copy the code
  • The second way to create a specified date and time is to parse a string in ISO 8601 format:
var d = Date.parse('the 2015-06-24 T19:49:22. 875 + 08:00');
d; / / 1435146562875
Copy the code
  • But instead of a Date object, it returns a timestamp. But with a timestamp you can easily convert it to a Date:
var d = new Date(1435146562875);
d; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)
d.getMonth(); / / 5
Copy the code
  • When date.parse () is used, the string passed in uses the actual month 01 to 12. After being converted to a Date object, getMonth() obtains the month value from 0 to 11
  • JavaScript Date objects start with month values at 0, keeping in mind that 0= January, 1= February, 2= March… In December, 11 =

JSON

  • Number: exactly the same as the JavaScript number;
  • Boolean: is JavaScript true or false;
  • String: is JavaScript string;
  • Null: is JavaScript null;
  • Array: is the JavaScript array representation — [];
  • Object: is JavaScript {… } representation.For uniform parsing, JSON strings must be quoted as "", and Object keys must be quoted as "".

serialization

  • JSON.stringify
var xiaoming = {
    name: 'Ming'.age: 14.gender: true.height: 1.65.grade: null.'middle-school': '\"W3C\" Middle School'.skills: ['JavaScript'.'Java'.'Python'.'Lisp']};Copy the code

Change to json.stringify (xiaoming, null, “”);

{
  "name": "Xiao Ming"."age": 14."gender": true."height": 1.65."grade": null."middle-school": "\"W3C\" Middle School"."skills": [
    "JavaScript"."Java"."Python"."Lisp"]}Copy the code

The second argument controls how to filter the key of the object. If we only want to output the specified property, we can pass Array

JSON.stringify(xiaoming, ['name', 'skills'], ' '); Results: {" name ":" Ming "and" skills ": [" JavaScript", "Java", "Python", "Lisp"]}Copy the code

We can also pass a function in which each key-value pair of an object is processed first:

function convert(key, value) {
    if (typeof value === 'string') {
        return value.toUpperCase();
    }
    return value;
}
JSON.stringify(xiaoming, convert, '  ');
Copy the code

The above code changes all attribute values to uppercase:

{
  "name": "Xiao Ming"."age": 14."gender": true."height": 1.65."grade": null."middle-school": "\"W3C\" MIDDLE SCHOOL"."skills": [
    "JAVASCRIPT"."JAVA"."PYTHON"."LISP"]}Copy the code

ToJSON ()** toJSON()** toJSON()** toJSON()**

var xiaoming = {
    name: 'Ming'.age: 14.gender: true.height: 1.65.grade: null.'middle-school': '\"W3C\" Middle School'.skills: ['JavaScript'.'Java'.'Python'.'Lisp'].toJSON: function () {
        return { // Print only name and age, and change key:
            'Name': this.name,
            'Age': this.age }; }};Copy the code
JSON.stringify(xiaoming); // '{"Name":" Age":14}'Copy the code

deserialization

Parse () takes a JSON string and turns it into a JavaScript object with json.parse () :

JSON.parse('[1, 2, 3, true]'); // [1, 2, 3, true]
JSON.parse('{" name ", "Ming", "age" : 14}'); // Object {name: 'xiao Ming ', age: 14}
JSON.parse('true'); // true
JSON.parse('123.45'); / / 123.45
JSON.parse() can also accept a function to convert parsed attributes:Copy the code
'use strict';
var obj = JSON.parse('{" name ", "Ming", "age" : 14}'.function (key, value) {
    if (key === 'name') {
        return value + 'students';
    }
    return value;
});
console.log(JSON.stringify(obj)); // {name: '小 小 学', age: 14}

{"name":"Xiao Ming"."age":14}
Copy the code

The browser

Size of the viewable area of the browser window

  • Get the size of the browser window (the viewport of the browser, excluding toolbars and scrollbars) :
  1. For IE9+, Chrome, Firefox, Opera, and Safari:
• window.innerheight - the innerHeight of the browser window • window.innerwidth - the innerWidth of the browser windowCopy the code
  1. For Internet Explorer 8, 7, 6, 5:
• document. DocumentElement. ClientHeight said HTML document in the current height of the window. • document. DocumentElement. ClientWidth said HTML document in the current width of the window.Copy the code
  • The body property of the Document object corresponds to the tag of the HTML Document
• document. Body. ClientHeight • document. Body. ClientWidthCopy the code
  • JavaScript schemes that work in different browsers:
var w= document.documentElement.clientWidth
      || document.body.clientWidth;
var h= document.documentElement.clientHeight
      || document.body.clientHeight;
Copy the code

Page size scrollHeight

  • ScrollHeight and scrollWidth, get the height and width of the web page content.

I. For IE and Opera:

  • ScrollHeight is the actual height of the web page content, which can be smaller than the clientHeight.

2. For NS and FF:

  • ScrollHeight is the height of the page content, but the minimum value is clientHeight. That is, scrollHeight returns clientHeight if the actual height of the page content is less than the clientHeight.

Third, browser compatibility

var w=document.documentElement.scrollWidth
   || document.body.scrollWidth;
var h=document.documentElement.scrollHeight
   || document.body.scrollHeight;
Copy the code

Note: case sensitive

  • ScrollHeight and scrollWidth also get the actual height and width of the content in the Dom element

Page size offsetHeight

OffsetHeight and offsetWidth, get the height and width of the page content (including edges such as scroll bars, which change with the display size of the window).

The distance and offset of the page

ScrollLeft: Sets or gets the distance between the left edge of a given object and the leftmost portion of the currently visible content in the window, the gray content on the left. ScrollTop: Sets or gets the distance between the top of the object and the top of the visible content in the window, that is, the gray content above. OffsetLeft: Gets the computed left position of the specified object relative to the layout or parent coordinates specified by the offsetParent property. OffsetTop: Gets the computed top position of the specified object relative to the parent coordinate of the layout or as specified by the offsetParent property.Copy the code
  1. Case sensitive
  2. OffsetParent: The parent container in which postion attributes (Relative, Absolute, fixed) are set, starting with the nearest parent node and working up to the body of the HTML. A, values,
OffsetHeight = clientHeight + scroll bar + border.Copy the code

Second, browser compatibility

var w= document.documentElement.offsetWidth
    || document.body.offsetWidth;
var h= document.documentElement.offsetHeight
    || document.body.offsetHeight;
Copy the code

Browser BOM Object

Window object method

  • The Window object not only acts as a global object, but also represents the browser window;
  • The window object has the innerWidth and innerHeight properties to get the internal width and height of the browser window
  • OuterWidth and outerHeight properties to get the entire width and height of the browser window.

JavaScript- Open a new window (window.open)

  • The open() method finds an existing or newly created browser window.
Window.open ([URL], [window name], [parameter string])Copy the code

navigator

The navigator object represents information about the browser. The most commonly used properties include:

  • Navigator. appName: browser name;
  • Navigator. appVersion: Browser version;
  • Navigator. language: the language in which the browser is set;
  • Navigator. platform: Operating system type;
  • Navigator. userAgent: user-agent string set by the browser.
console.log('appName = ' + navigator.appName);
console.log('appVersion = ' + navigator.appVersion);
console.log('language = ' + navigator.language);
console.log('platform = ' + navigator.platform);
console.log('userAgent = ' + navigator.userAgent);
Copy the code

screen

The screen object represents screen information. Common properties are:

  • Screen. width: screen width, in pixels;
  • Screen. height: Screen height, in pixels;
  • Screen. colorDepth: Returns the color number, such as 8, 16, and 24.

document

  • The Document object represents the current page. Because HTML is represented as a tree in the BROWSER as a DOM, the Document object is the root node of the entire DOM tree.
  • The document title attribute is read from XXX in the HTML document, but can change dynamically:
'use strict'; Document.title = 'Learn JavaScript hard! ';Copy the code
  • GetElementById () and getElementsByTagName() get a DOM node by ID and a set of DOM nodes by Tag name

cookie

The Document object also has a cookie property that retrieves the cookie of the current page. A Cookie is a key-value identifier sent by the server. Because HTTP protocol is stateless, but the server to distinguish which user sent the request, can use cookies to distinguish. When a user successfully logs in, the server sends a Cookie to the browser, such as user=ABC123XYZ(encrypted string)… After that, when the browser visits the website, it will attach the Cookie in the request header, and the server can distinguish users according to the Cookie.

  • Cookies can also store some of the site’s Settings, such as the language in which the page is displayed.
  • JavaScript can read the cookie of the current page via document.cookie:
  document.cookie; // 'v=123; remember=true; prefer=zh'
Copy the code
  • The server can use httpOnly when setting cookies. Cookies that are set to httpOnly cannot be read by JavaScript.
  • This behavior is implemented by browsers. Mainstream browsers support httpOnly. To ensure security, the server should always use httpOnly when setting cookies.

Wide screen high

  • The window.screen object contains information about the user’s screen.

  • Screen. height Returns the high resolution of the screen

  • Screen.width Returns the width of the screen resolution

  • Units are in pixels.

  • Window.screen objects can be written without the window prefix. Let’s get the height and width of the screen as follows:

<script type="text/javascript">
  document.write( "Screen width:"+screen.width+"px<br />" );
  document.write( "Screen height:"+screen.height+"px<br />" );
<\/script>
Copy the code

Screen height and width available

  • The screen.availWidth property returns the width of the visitor’s screen, in pixels, minus interface features, such as the taskbar.

  • The screen.availHeight property returns the height of the visitor’s screen, in pixels, minus interface features, such as the task bar.

  • The default height of the taskbar varies from system to system, and the position of the taskbar can be anywhere on the screen, so the available width and height may be different. Let’s get the available height and width of the screen as follows:

<span class="lf"><br><span class="hd-lf" style="display: none">
</span></span>document.write("Available width:"+ screen.availWidth); <span class="lf"><br><span class="hd-lf" style="display: none">
</span></span>document.write("Usable height:"+ screen.availHeight); <span class="lf"><br><span class="hd-lf" style="display: none">
</span></span>
Copy the code

DOM manipulation

NodeList class array object

  • Saves an ordered set of nodes
  • It is accessible by square bracket syntax and has the item method and length attribute
  • You can output an array of classes using childNodes

HTMLCollection class array object

  • Provides easy access to document elements such as forms, images, and links
  • It can be used to retrieve elements by their position in the document or by their ID or name attributes
  • document.getElementsByTagName()
  • document.images
  • document.scripts
  • document.links
  • document.forms
  • There is a namedItem method that returns an element with id xx and an element with name xx if there is none.
  • The item() method is used to retrieve objects at a specified position in the collection

NameNodeMap class array object

  • Attribute is a collection of attribute elements
  • throughEle.attributesTo obtain
  • The item() method is used to retrieve objects at a specified position in the collection

Create DOM

  • document.createElement()New Element node method that returns an Element object and implements HTML5 tags.
  • document.createTextNode()Create a Text node (returns the newly created Text node)
  • document.createDocumentFragment()Creating a document fragment
  • document.createent()Pass in a comment node
  • ele.innerHTMLSets or gets the content between start and end tags. insertscriptThere are limits
  • ele.outerHTMLReturns the HTML tag for the element calling it and all its children
  • innerTextSets or gets all text nodes between the start and end tags, which are replaced so that the tags are also displayed as text
  • outerTextSets or gets the text node of the element calling it and all its children, replacing the label with text as well
  • textContentIt works in Firefox, which automatically htML-encodes strings and ensures that no HTML tags can be set.
  • The difference is that when reading an attribute, innerText does not return the text of the hidden element, while textContent returns all of the text. (Also note that IE<9 does not support textContent)
  • outerHtML

Select the DOM

  • firstChild
  • firstElementChild
  • lastElementChild
  • nextElementSibling
  • previousElementSibling
  • Children [0] traverses all element nodes
  • ownerDocument
  • ChildElementCount returns the number of children of an element
  • ChildNodes retrieves all childNodes

Find the DOM

- document.getElementById() // The result is a div element object
- document.getElementsByName() // Returns a collection of node objects, resulting in an array of classes
- document.getElementsByTagName() // Returns a collection of node objects with the specified label name,'*' all elements,'! 'Comment element
- document.getElementsByClassName() // The method returns a collection of objects with the specified class name, with a subscript if you want to get an element
- document.querySelector() // CSS selector, null if it does not exist
- document.querySelectorAll() // If not, return [] empty collection
- nodeObject.nextSibling // Next sibling node
- nodeObject.previousSibling // Previous sibling node
Copy the code
  • The ID is unique in the HTML document
  • sodocument.getElementById()You can directly locate a single DOM node.
  • Document. The getElementsByTagName () and the document. The getElementsByClassName () always returns a set of DOM node.
  • To select the DOM accurately, locate the parent node first and then select from the parent node to narrow the selection.
var test = document.getElementById('test');// Return the node with ID 'test'
var trs = document.getElementById('test-table').getElementsByTagName('tr');
// Locate the node whose ID is 'test-table' and return all its tr nodes

var reds = document.getElementById('test-div').getElementsByClassName('red');
// locate the node whose ID is 'test-div' and return all nodes whose class contains red

var cs = test.children();
// Get all immediate children of node test:

var first = test.firstElementChild();
var last = test.lastElementChild();
// Get the first and last child node of test:

var q1 = document.querySelector('#q1');
// Get the node with ID Q1 via querySelector
var ps = q1.querySelectorAll('div.highlighted > p');
QuerySelectorAll = querySelectorAll
Copy the code

Operating the DOM

appendChild

  • Adds a child node as the last child of the parent node.
  • If the inserted JS node already exists in the current document tree, the node is removed from its original position and inserted into the new position (clipping operation).
  • Typically, a new node is created from zero, inserted at the specified location, and the newly inserted node is returned
var list = document.getElementById('list'),
    haskell = document.createElement('p');// Create the p tag

haskell.id = 'haskell';
haskell.innerText = 'Haskell';
list.appendChild(haskell); // Insert as the last child of the list
Copy the code

insertBefore

  • Insert new child nodes before existing child nodes,NewElement parentElement. InsertBefore (new node, reference position referenceElement);
  • Child nodes are inserted before the referenceElement, returning the newly inserted node
  • The second argument is null is implementableappendChild()methods
  • The second parameter xx. FirstElementsChild can be implemented before inserting the first node
  • The second parameter is xx. LastElementsChild can be implemented before inserting the last node

replaceChild()

  • Replace the child node of the element with a new node. The replaced node must be the child node of the node using the method
  • El.replacechild (node to be inserted, node to be replaced), returns the replaced node
node.replaceChild (newnode,oldnew ) 
Copy the code

cloneNode()

  • Creates a copy of the node and returns the copy
  • The copied node must have a parent node. If it does not have a parent node, you need to add it in some way
  • Parameter Boolean, default false, does not copy child nodes

normalize()

  • Merge adjacent texts
  • div.normalize()Div text merge

splitText()

  • Splits the text node into two nodes at the specified location and returns the new node
  • Div.firstchild.splittext (5) takes an argument, truncated before a number

Delete the DOM

removeChild()

  • Must have an argument to return the deleted child node
// Get the node to be deleted:
var self = document.getElementById('toRemove');
// Get the parent node:
var parent = self.parentElement;
/ / remove:
var removed = parent.removeChild(self);
removed === self; // true
Copy the code
  • Notice that the deleted node is no longer in the document tree, but it is still in memory and can be added to another location at any time.
  • Be careful when traversing the children of a parent and deleting themchildrenA property is aRead-only propertyAnd it changes when the child node changesLive updates.

removeNode()

  • Private implementation of IE
  • Delete the target node from the document and return to the target node
  • Parameter Boolean, default false, deletes only the target node, keeps child nodes

Setting element Styles

-ele.style. styleName = styleValue name Set style name,Value set styleValueCopy the code

Add the class

  • ele.className()Returns the class attribute of the element
  • ele.className=''Sets the class attribute of the ele element
  • classNameReset the class, the original is replaced;

DOM attributes

Intrinsic properties

Custom attributes

  • Properties that the browser binds to elements in advance are called inherent Properties and can be viewed in the Console Properties area
  • Can’t pass.Method, return undefined
  • Custom attributes are automatically converted to all lowercase
  • Custom attribute with the same name attribute, the following is killed
  • div.attributes.getNamedItem('xxx').nodeValueGets the specified property node
  • div.attributes.getNamedItem('id').nodeValueGets the specified property node
  • div.attributes['id'].nodeValueGets the specified property node
  • div.attributes.removeNamedItem('yyy')To remove ayyyProperties.
  • Create a custom property:
var attr = document.createAttribute('data-title');
attr.value = 'ddd'
div.attributes.setNamedItem(attr)
Copy the code

Action attribute

  • For native attributesTags. AttributesI can get properties,Tags. The classWith the exception of
- obtain elementNode. GetAttribute ("name")  // Get the value of the attribute with the specified attribute name from the element node
elementNode.name
// There is a difference between getting style and onclick.- set elementNode. SetAttribute ("Attribute name"."Attribute value") // Adds the specified attribute to the element and assigns a value, or sets an existing attribute to the specified value- delete elementNode. RemoveAttribute ("name") // Enter the property name to delete the property
Copy the code

Node properties

In the Document Object Model (DOM), each node is an object. DOM nodes have three important properties:

  1. NodeName: indicates the nodeName
  2. NodeValue: specifies the nodeValue
  3. NodeType: nodeType

NodeName property: The name of the node, which is read-only.

  1. The nodeName of the element node is the same as the label name
  2. The nodeName of the property node is the name of the property
  3. The nodeName of a text node is always #text
  4. The nodeName of the document node is always #document

NodeValue: nodeValue

  1. The nodeValue of the element node is undefined or null
  2. The nodeValue of a text node is the text itself
  3. The nodeValue of an attribute node is the value of the attribute

NodeType property: The type of the node is read-only:

Element type Node type element1attribute2The text3annotation8The document9
Copy the code

String properties

  • Common attributes:id,class,title,href,src,lang,dir,naem,value,accesskey
  • <bod dir= "RTL"></bod>
  • classNameYou can set the class
  • Data is obtained using the dataset
  • There are methods in classList:ele.classList.add().ele.classList.remove().ele.classList.toggle().
  • ele.classList.contains()

Operation form

The input controls for HTML forms are as follows:

  • Text box, corresponding to, for input text;
  • Password box, corresponding to, for entering a password;
  • Single click box, corresponding to, used to select an item;
  • Check box corresponding to, used to select multiple items;
  • The drop-down box, corresponding to, is used to select an item; Hidden text, corresponding toThe user is not visible, but the hidden text is sent to the server when the form is submitted.

Get the value

  • Acquire aValue can be directly called to obtain the corresponding user input value:
var input = document.getElementById('email');
input.value; // 'user input value'
Copy the code

For checkboxes and checkboxes, the value property always returns the HTML default value, and what we really need to get is whether the user “checked” the option, so we should use checked:

// Monday
// Tuesday
var mon = document.getElementById('monday');
var tue = document.getElementById('tuesday');
mon.value; / / '1'
tue.value; / / '2'
mon.checked; // true or false
tue.checked; // true or false
Copy the code

Set the value

Setting a value is similar to getting a value. For text, password, hidden, and SELECT, set value directly:

var input = document.getElementById('email');
input.value = '[email protected]'; // The content of the text box is updated
	// For checkboxes and checkboxes, set Checked to true or false
Copy the code

It controls

Date, datetime, datetime-local, color, etc., all use input tags:

2015/07/01
input type="date" value="2015-07-01"
 
2015/07/01 02:03:04
input type="datetime-local" value="2015-07-01T02:03:04"
Copy the code
  • Browsers that do not support HTML5 will not recognize the new controls and will treat them astype="text"To display.
  • Html5-enabled browsers will get formatted strings. For example, an input value of type=”date” is guaranteed to be a valid date in YYYY-MM-DD format, or an empty string.

Submit the form

  • One is to submit a form via the element’s submit() method. For example, submit the form in JavaScript code in response to a click event:
    form id="test-form"
    input type="text" name="test"
    button type="button" onclick="doSubmitForm()">Submit
    from
    
    function doSubmitForm() {
        var form = document.getElementById('test-form');
        // You can modify the form input here...
        rm:
        form.submit();
    }
    
Copy the code

The downside of this approach is that it disrupts the browser’s normal submission of the form. By default, the browser submits the form when clicked, or the user presses enter on the last input box. Therefore, the second way is to respond to its own onSubmit event and modify it when submitting the form:


    
    button type="submit">Submit button

function checkForm() {
    var form = document.getElementById('test-form');
    // You can modify the form input here...
    // Proceed to the next step:
    return true;
}
Copy the code
  • Note that return true tells the browser to continue. If return false,
  • The browser will not continue to submit the form. In this case, the user enters an error message and terminates the submission of the form.
  • Make full use of **** to pass data when reviewing and modifying.

Many login forms expect the user to enter a user name and password, but, for security reasons, submit the form without transmitting a plain-text password, but instead with MD5 of the password. Generic JavaScript developers will directly modify:

    form id="login-form" method="post" onsubmit="return checkForm()">
    
    input type="password" id="password" name="password">
    Submit
    from>
    
function checkForm() {
    var pwd = document.getElementById('password'); Change the plaintext toMD5: pwd.value = toMD5(pwd.value); Moving on to the next step:return true;
}

Copy the code
  • This seems fine, but when the user enters a password to submit, the password box will suddenly change from severalBecome a 32(Because MD5 has 32 characters).

To avoid changing user input, you can implement:

form id="login-form" method="post" onsubmit="return checkForm()">
    
input type="password" id="input-password">
    
button type="submit">Submit


function checkForm() {
    var input_pwd = document.getElementById('input-password');
    var md5_pwd = document.getElementById('md5-password'); Change the plaintext toMD5: md5_pwd.value = toMD5(input_pwd.value); Moving on to the next step:return true;
}

Copy the code

Note that the id of md5-password is marked with name=”password”, and the id of input-password entered by the user does not have the name attribute. Data without the name attribute will not be submitted

Operation file

  • In an HTML form, the only control that can upload a file is
  • Note: When a form contains, the encType of the form must be specified as multipart/form-data, and method must be specified as POST for the browser to properly encode and send the form’s data in multipart/form-data format.
  • For security reasons, browsers only allow usersClick on theTo select local files using JavaScript pairstheThe value assignmentIt doesn’t have any effect. The uploaded files are processed by the background server. JavaScript can check the file extension when submitting the form to prevent users from uploading invalid files:
var f = document.getElementById('test-file-upload');
var filename = f.value; // 'C:\fakepath\test.png'
if(! filename || ! (filename.endsWith('.jpg') || filename.endsWith('.png') || filename.endsWith('.gif'))) {
    alert('Can only upload image file.');
    return false;
}
Copy the code

File API

Because JavaScript has very limited operation on files uploaded by users, especially cannot read the contents of files, many web pages that need to operate files have to be realized by third-party plug-ins like Flash. With the popularity of HTML5, the new File API allows JavaScript to read the contents of a File and get more information about a File. HTML5’s File API provides two main objects, File and FileReader, to get File information and read the File.

The following example shows how to read a user-selected image file and preview the image in a:

var
    fileInput = document.getElementById('test-image-file'),
    info = document.getElementById('test-file-info'),
    preview = document.getElementById('test-image-preview');
// Listen to the change event:
fileInput.addEventListener('change'.function () {
    // Clear the background image:
    preview.style.backgroundImage = ' ';
    // Check whether the file is selected:
    if(! fileInput.value) { info.innerHTML ='No file selected';
        return;
    }
    // Get a File reference:
    var file = fileInput.files[0];
    // Get File info:
    info.innerHTML = 'File:' + file.name + ' ' +
                     'Size:' + file.size + ' ' +
                     'Modify:' + file.lastModifiedDate;
    if(file.type ! = ='image/jpeg'&& file.type ! = ='image/png'&& file.type ! = ='image/gif') {
        alert('Not a valid picture file! ');
        return;
    }
    // Read the file:
    var reader = new FileReader();
    reader.onload = function(e) {
        var
            data = e.target.result; // 'data:image/jpeg; base64,/9j/4AAQSk... (base64 encoding)... '
        preview.style.backgroundImage = 'url(' + data + ') ';
    };
    // Read the file as a DataURL:
    reader.readAsDataURL(file);
});
Copy the code
  • The above code demonstrates how to read the contents of a File through HTML5’s File API. The file read as a DataURL is a string similar to data:image/ JPEG; base64,/9j/4AAQSk… (base64 encoding)… , often used to set images. If server-side processing is required, the binary contents of the original file can be obtained by sending the string base64 to the server and decoding it with base64.

The callback

  • The above code also demonstrates that an important feature of JavaScript is the single-threaded execution mode. In JavaScript, the browser’s JavaScript execution engine always executes JavaScript code in single-threaded mode, meaning that JavaScript code can never be executed by more than one thread at a time.

You may be asking, how does JavaScript that executes in single-threaded mode handle multitasking?

  • In JavaScript, multitasking is really all aboutThe asynchronous call, such as the code above:reader.readAsDataURL(file)

An asynchronous operation is initiated to read the contents of the file. Since the operation is asynchronous, we don’t know when the operation ends in JavaScript code, so we need to set up a callback function first:

reader.onload = function(e) {// When the file is read, this function is automatically called:};Copy the code

When the file is finished reading, the JavaScript engine automatically calls the callback function we set up. When the callback function is executed, the file has already been read, so we can safely retrieve the file contents inside the callback function.

BOM

BOM Browser object model

Windows object

  • All global variables and methods are on the window
  • A window is either an interface to access a browser through JavaScript or a Global object as defined in ECMAScript

Window object method

  • window.alert('content')A warning box is displayed
  • window.confirm('message')Displays a dialog box with the specified message and OK and cancel: true for confirm, false for cancel
window.confirm("Are you sure you want to delete it?")
Copy the code
  • window.prompt()The input box pops up: If you confirm, the input content will be returned. If you click Cancel, null will be returned.
var mes = prompt("Please enter your star sign :"."Virgo");
console.log(message);
Copy the code
  • window.open(pageURL,name,parameters)Open a new browser window or find a named window
  • The three parameters represent the child window path, child window handle, and window parameters (separated by commas).
  • window.close()Close the Browser window

Timeout calls setTimeout

SetInterval (code,millisec);

  1. Code: The function to call or the code string to execute
  2. Zipcodes: the time interval between the periodic execution or invocation of expressions, in milliseconds (1s=1000ms). Return value: an ID that can be passed to clearInterval() to cancel periodic execution of the code.
setTimeout(function(){
	alert("hello");
},2000) -- -- -- -- -- -- -- -- --var fnCall = function(){
	alert("hello");	
}
setTimeout(fnCall,2000);
Copy the code
  • clearTimeout(id_of_setTimeout)Clear timeout calls
Syntax: clearTimeout(id_of_setTimeout) Parameter description: id_of_setTimeout: ID returned by setTimeout().Copy the code
  • SetTimeout () only executes once. If you want to execute more than once, the call itself will do;

Call setInterval(code,millisec)

  • Execute code at specified intervals in milliseconds
setInterval(function(){
	num++;
},1000)
Copy the code
  • clearInterval(id_of_setInterval)Clear intermittent calls;

location

The location attribute

  • Location provides information about the current window loading document, which is both a window and a document property;
  • You can uselocation.hrefTo get a full URL:
http://www.example.com:8080/path/index.html?a=1&b=2#TOP
Copy the code
  • To get the values for each part of the URL, write:
location.protocol; // 'HTTP' returns the protocol used by the page;
location.host; // 'www.example.com' returns the server name and port number, if any;
location.port; // '8080' returns the port number;
location.pathname; // '/path/index.html' returns the directory and file name in the URL;
location.search; / / '? A =1&b=2' returns the query string for the URL, starting with a question mark;
location.hash; // '#TOP' returns anchor;
Copy the code

Location object

  • Location operations: location.href
setTimeout(function(){
	location.href ='index7.html'
},1000)
Copy the code
  • You can also change the URL: location.hash location.search

  • Location.replace (‘url’) redirects the URL, no history is generated location.replace(‘index7.html’)

  • If you want to reload the current page, calling the location.reload() method is handy.

  • Location.reload (true) reloads from the server; Put it on the last line

The history method (back)

The history object records the pages (urls) that the user has visited and enables the browser to navigate backwards and forwards in a similar way.

Note: Every browser window, every TAB, and even every frame has its own history object with a specific history from the moment the window is openedwindowObject association.windowNote: properties | methods. History. []windowCan be omittedCopy the code

History object property

  • The history object holds a history of pages accessed by the user in the browser
Go (-n) location.forward() : returns the number of urls in the browser history table column; Back () loads the previous URL in the listwindow.history.javascript();
window.history.forward(); Go () loads a specific pagewindow.history.go(number);
Copy the code

Location object

Location is used to get or set the FORM’s URL, and can be used to parse the URL.

[properties | methods] syntax: the location.Copy the code

Location object properties: location object properties:

The screen object

The screen object is used to get screen information about the user. Screen width and height:

  • screen.availWidth()
  • screen.availHeught()

Window width and height:

  • window.innerWidth()
  • window.innerHeight()
Syntax: window.screen. propertyCopy the code

The Navigator object

  • The Navigator object contains information about the browser and is typically used to detect the browser versus the operating system version
  • The userAgent property of the Navigator object identifies the browser name, version, engine, and operating system
console.log(navigator.userAgent);
Copy the code

The event

  • Documents and browsers interact instantaneously
  • In the event-triggering function,this is a reference to this DOM element
  • The event object
  • The event object binds an event type
  • Event handlers

Flow of events

Event delegation

  • Event delegate is to use the bubbling principle, add the event to the parent level, trigger the execution effect
  • Using event delegates can improve performance

HTML event

  • <button onclick = "alertWindow()"> </button>Disadvantages:
  1. Binding multiple elements to the same event is inefficient
  2. It is not recommended to write JS in HTML
  3. Strong coupling is not conducive to code reuse

DOM0 level events

Syntax :ele. Event = execute script

  • Gets the HTML element and binds the event to the DOM object
  • It can be an anonymous function or a function call
  • A handler that assigns a function to another time
  • Simple and cross-browser usable
  • Multiple sequential triggers can be added
  • One and only one event type can be bound
var btn =..... // Select the element
btn.onclik = function () {
	console.log(this)
	This is a reference to a Dom element
}
btn.onclick = null; // Remove the onclick attribute
Copy the code

DOM2 level event processing

  1. AddEventListeber () to add
  2. btn2.addEventListener('click',function () {},false)Two functions take three arguments ()
  3. The name of the event to be handled, as a function of the event handler, with a Boolean value true to capture phase calls, or vice versa.
  4. Delete removeEventListner ()
  5. btn2.removeEventListener('click',dom2)The main reason for the successful unbinding is that the parameters in the function are consistent
  6. No + ‘on’ required
  7. Multiple sequential triggers can be added
  8. Benefits: Loose coupling, binding of multiple events, event capture, and bubbling

IE event handler

  • The default event bubbles
  • AttachEvent () adds events. You can add more than one
  • DetachEvent () deletes the event
var click = function () {
	alert("clicked")
}

btn.attachEvent("onclick",click);

btn.datachEvent("onclick",click)

Copy the code
  • The function takes two two-parameters: the name of the event handler and the function of the event handler
  • The anonymous function this points to the window

Cross-browser processing

    var EventUtil = {
// Add a handle
    	addHandler:function (element,type,handler) {
    		if (element.addEventListener) {
    			element.addEventListener(type,handler,false)}else if(element.attachEvent){
    			element.attachEvent('on' + type,handler)
    		} else {
    		 	element['on'+type] = handler
    		}
    	},

// Delete the handle
    	removeHandler:function (element,type,handler) {
    		if (element.removeEventListener) {
    			element.removeEventListener(type,handler,false)}else if(element.detachEvent){
    			element.detachEvent('on' + type,handler)
    		} else {
    		 	element['on'+type] = null}}}Copy the code

The difference between:

  • Internet Explorer uses bubble events Netscape uses capture events and DOM uses capture after bubble events
  • Bubble event model: Button ->div->body (IE event stream)
  • Capture event model: body->div-> Button (Netscape event stream)
  • DOM event model: body->div->button->button->div->body
  • In IE8 and below, events contain on, but DOM does not

Event object

Event objects in the DOM

  • Event. type Indicates the event type
  • Event. target Target object, event source object, added to what
  • Event.currenttarget The binding object of the event
  • Event.stoppropagation () prevents events from bubbling or being captured
var click = function (event) {
	alert("clicked")
	event.stopPropagation()
}
Copy the code
  • Event.preventdefault () prevents the default behavior
  • Event. cancelable Whether the default behavior of an event can be cancelled
  • Detail Details about an event

The Event clientY, pageY, screenY

  • ClientY browser top bottom edge to mouse position, does not count scroll wheelbase away
  • PageY browser top bottom edge to mouse position, but it calculates scroll wheelbase away
  • ScreenY Top of the screen to mouse position

Event objects in IE

  • attachEventThe binding event
  1. event.typeProperty to get the event type
  2. srcElementProperty is used to get the target of the event, to what
  3. event.cancelBubble = tureProperty to prevent events from bubbling: true prevents bubbling, false does not prevent bubbling
  4. event.returnValue = falseProperty to block the default behavior of the event: false blocks the default behavior of the event

The event type

UI events

  • Load completed
EventUtil.addHandler(window."load".function (e) {
	alert("Loaded")})Copy the code
  • Unload switches from one to another
  • Resize The window size changes
  • Scroll trigger event, repeated trigger, loss performance!

“Event”

  • Lose focus
  • Focusout loses focus
  • Focus Obtains the focus and does not support bubbling
  • Focusin gets focus and supports bubbling

Mouse events

  • Event. button == 0 Left mouse button

  • Event. button == 1 mouse

  • Event. button == 2 Mouse right click

  • Click =” function ()”

  • Double-click the event dblclick

  • Mousedown the event mousedown

  • Mouse release event mouseup

  • Mouse movement event mousemove

  • Mouse away from target element or child element event mouseout,

  • The mouse enters the target element or child element event mouseover

  • Only the target element mouseEnter can be entered

  • You can only leave the target element mouseleave

  • Submit occurs when the form confirmation button is clicked, not on the button but on the form

  • Content Select event SELECT

  • ClientX and clientY mouse get position

  • Select event, when the text in the text field or text box is selected, the select event is triggered, and the called program is executed.

  • Text box content change event (change) Changes the contents of a text box to trigger the change event, while executing the called program.

  • Select,checkbox, radio, etc.

  • Repeated trigger when elements are moved inside

Keyboard events

  • keyCode: Returns the key value when pressed
  • onkeydown: Press any key
(event accepts event objects as arguments) represents the state of the eventdocument.onkeydown = function(event){
	console.log(event.keyCode);
	}
Copy the code
  • onkeypress: Press on the keyboardThe characters of the key(ASCII event.charcode)
  • onkeyup: occurs when a keyboard key is released
  • textInputThe value of the input

Special event

  • DOMNodeInsertedAdd any event trigger to the xx element
  • DOMNodeRemovedRemoves any event trigger from the xx element
EventUtil.addHandler(document."DOMNodeRemoved".function () {
	console.log('Document has elements deleted')})document.body.removeChild(myText);
Copy the code
  • DOMSubtreeModifiedAny change in the document structure is triggered.
EventUtil.addHandler(document."DOMSubtreeModified".function () {
	console.log('Document has a structure change')})Copy the code
  • Before triggers DOMNodeRemovedFromDocument removed from the document

  • Add will trigger before DOMNodeInsertedIntoDocument from the document

  • DOMContentLoaded fires behind the DOM tree, regardless of whether images,javascript files.CSS files or other resources have been downloaded

  • readystatechange

  • Hashchange can only be added in Windows, and a change in the value after the # triggers: event.oldurl + event.newurl

Mobile event type

  • Touchstart: Touch the screen with a finger

  • Event.touches

  • The Event.ChangedTouches array contains information about the touch points that caused the event

  • Event.targettouches contains only the touch point information placed on the element

  • Touchmove: Swiping a finger across the screen

  • Touchend: Finger moves away from the screen

  • Touchcancel Is triggered when the system stops tracking a touch