The content of this chapter is based on JavaScript (variables, data types, operators, flow statements, arrays, functions, string functions, regular expressions, DOM basic operations, Window objects, JS objects, JSON, cookies). The study notes that the blogger sorted out before, if there are any mistakes, Ask everybody to give directions greatly

Introduction to the

Introduction of 0.

JavaScript programs the behavior of web pages

Javascript is a scripting language and a lightweight programming language

JavaScript is a dynamically typed language, while Java is a statically typed language

JavaScript is weakly typed, Java is strongly typed

1. Naming conventions

  • Case sensitive

  • The first character must be a letter, underscore (_), or a dollar sign ($); Other characters can be letters, underscores, dollar signs, or numbers

  • Must not contain Spaces or other punctuation marks.

  • Cannot be named after a keyword or reserved word

2. Write specifications

  1. The smallest unit of indentation is 4 Spaces

  2. All variables should be declared before use

  3. The name should consist of 26 upper and lower case letters (A.. Z, a .. Z), 10 numbers (0.. 9) and _(underscore). Do not use $(dollar sign) or backslash in names.

Use 3.

1. JavaScript code must be placed between the < script > and </ script > tags.

<script>
  document.getElementById("demo").innerHTML = "My first JavaScript";
</script>
Copy the code

2. JavaScript files place external script references.

<script src="myScript.js"></script>
Copy the code

Advantages of external JavaScript:

Separate HTML from code. Make HTML and JavaScript easier to read and maintain. Cache JavaScript files to speed up page loading

4. Comment

// single-line comment /* */ multi-line comment

5. The output

The output

Code | explanation – | – | – window. The alert () | document. The pop-up warning box 】 【 the write () | 】 【 write content to HTML document innerHTML | 【 】 in written to the HTML console. The log () | “written to the browser console”

Console. log(‘ text message ‘); Console. info(‘ info ‘); Console. warn(‘ warning messages ‘); Console. error(‘ error message ‘);

Statement identifiers (keywords)

Keyword | explanation – | – | – break | to jump out of the loop. Catch | blocks, and executed when something goes wrong in the try block catch block. The continue | jump the an iterative cycle. do … While | executes a block in the conditional statement is true when continue to execute the statement block. For | in the conditional statement is true, can specify the number of blocks of code execution. for … In | to iterate through group or attribute of an object (an array or object attributes of cyclic operation). The function | define a function if… Else | used to perform different actions based on different conditions. Return exit function switch | | used to perform different actions based on different conditions. Throw | throw (generated) error. Try | implement error handling, used together with the catch. Var | declare a variable. While | when conditional statement is true, perform block.

variable

1. The variable

A variable is a memory used to store certain/certain values.

2. Naming method

2.1 Hungarian nomenclature

Variable name = type + object description

Named types Naming prefix
Array an array a
Boolean Boolean value b
Float float l
The function function fn
Int the integer i
object o
Regular regular r
String string s

For example:

var s_webname = 'hello world'
Copy the code

2.2 Camel nomenclature

When an identifier is joined by one or more words, the first letter of the first word is lowercase, the first letter of the next word is uppercase, and all other letters are lowercase.

For example:

var webName = 'hello world'
Copy the code

2.3 PASCAL nomenclature

It’s similar to camel nomenclature, but the first word is capitalized

For example:

var WebName = 'hello world'
Copy the code

3. Variable declaration

Var – Declares global variables

Let – Declares block-level variables, i.e. local variables. (I.e., declared variables are only valid within the code block in which the let command resides.)

Const – used to declare constants, also block-level scoped, or block-level declared. A variable declared by const may not change its value, which means that a const, once declared, must be initialized immediately and cannot be left for later assignment. Unrepeatable declaration.

4. Variable types

2. Data type →

5. Variable scope

In JavaScript, a scope is a collection of accessible variables.

JavaScript function scope: The scope is changed within the function.

The scope of a variable is the area in the program source code that defines the variable.

The JavaScript variable life cycle is initialized when it is declared.

Local variables are destroyed after the function completes execution. Global variables are destroyed after the page is closed.

5.1 Global Variables

A variable is defined outside a function and is a global variable.

Global variables have global scope: all scripts and functions in the web page can be used.

5.2 Local Variables

Variables are declared in functions and are local scopes.

Local variables take precedence over global variables of the same name

Local variables are created at the start of a function and destroyed automatically after the function is finished.

The data type

1. Data types

JavaScript data types (Symbol is new to ES6), divided into “base type” and “reference type”

Basic types: String, Number, Boolean, Null, Undefined

Reference types: Object, Array

Original type: Symbol

Null and undefined are generally considered special values, and these two types of values are unique in themselves.

Shows data type | — – | : – : | – : String (String) | use double quotes “or single quotation marks around one or more characters of digital (Number) | including integer and floating point Numbers (including decimal Number or scientific notation) Boolean (Boolean) | said true or false the two states Empty (Null) | variable or content value is empty (Null), can be to a variable assigned Null values to remove variable content Undefined (Undefined) | variable is created, not to the variable assignment, this type is only one value: Undefined Array (Array) | var cars = new Array (); Object (Object) | JavaScript Object notation (Symbol) | operation Symbol value generated by the Symbol function. Attribute names that belong to the Symbol type are unique and are guaranteed not to conflict with other attribute names. (the new command cannot be used before the PS: Symbol function, or an error will be reported.)

2. Js weakly typed language

JavaScript has dynamic typing, which means that the same variable can be of different types

Js is a weakly typed language and does not pay attention to the definition of a type, but JS will determine what type a variable is based on the assignment of a value to it.

3. Data type conversion

JavaScript has dynamic typing, so you don’t need to specify a data type and it will be converted automatically at execution

JavaScript variables can be converted to new variables or other data types:

  • By using JavaScript functions
  • Automatically converts through JavaScript itself

Number() is converted to a Number, String() to a String, and Boolean() to a Boolean value.

4. Data type judgment

4.1 Typeof operator

The typeof operator is used to detect the data typeof a variable.

  1. writing
  • The typeof () parentheses

  • Typeof Object with Spaces

  1. The type of data returned
  • number
  • string
  • boolean
  • object
  • undefined
  • function
  • Symbols

4.2 instanceof

Instanceof is really good for judging custom class instance objects, not native data types

function judgeType2 (obj) {
  if (obj === null) return "null";
  if (obj instanceof Array)  return "array";
  return (typeof obj);
} 
judgeType2("123")   // "string"
Copy the code

4.3 the Object. The prototype. ToString. Call ()

The use of the Object. The prototype. ToString. Call () method, can obtain the accurate type of variable.

console.log(Object.prototype.toString.call('asd'));  // [object String]
Copy the code

5. Null, undefined, NaN

1. null

Null stands for “null value”, represents an empty object pointer, uses typeof operation to get “object”, so you can think of it as a special object value.

2. undefined

Undefined means “undefined” and you can think of undefined as an empty variable.

3. NaN

NaN, that is, a non-numeric value, is a special value of type Number.

NaN features:

  1. Any operation that designs NaN returns NaN, a feature that can cause problems in multi-step calculations.
  2. NaN is not equal to any value, including itself.

Ps: ECMAScript defines the isNaN() function for these two features of NaN.

The operator

1. Arithmetic operators

+ (addition), – (subtraction), * (multiplication), / (division), % (mod), ++ (self-addition), — (self-subtraction)

// + (add)
console.log( 1 + 1) / / 2

// - (subtraction)
console.log( 2 - 1) / / 1

// * (multiply)
console.log( 2 * 2) / / 4

// / (division)
console.log( 4 / 2) / / 2

// % (mod)
console.log( 5 % 2) / / 1
Copy the code

2. The assignment operator

= (equals), +=, -=, *=, /=, %=

// = (equal to)
var a = 10 
console.log(a)  / / 10

/ / + =
var a = 10 
console.log(a+=1) / / 11

/ / - =
var a = 10 
console.log(a-=1) / / 9

/ / * =
var a = 10 
console.log(a*=2) / / 20

/ / / =
var a = 10 
console.log(a/=2) / / 5

/ / % =
var a = 10 
console.log(a%=3) / / 1
Copy the code

3. String operators

+ and + =

The + operator can also be used to add strings

The += assignment operator can also be used to add (cascade) strings

4. Relational (comparison) operators

(greater than), < (less than), >= (greater than or equal to), <= (less than or equal to),! = (not equal to), == (equal to), === (congruent),! === (really unequal)

PS: == compares only numeric values but not types

5. Logical operators

&& (logical and/and) : the result is true if both sides of the expression are true, otherwise false

| | (logical and/or) : when both sides have an expression is true, the result is true

! (Logical non/negation) : negation

6. Bit operators

The operator describe
& and
| or
~ The not
^ Exclusive or
<< Shift to the left
>> Moves to the right

7. Other operators

7.1 Ternary Operators (? 🙂

Conditions? The condition is established and executed: the condition is not established and executed;

2>1?console.log("true") :console.log("false")  // true
Copy the code

7.2 typeof

Data type, click here to jump to the corresponding location

7.3 a comma (,)

The comma operator concatenates several expressions. It has the lowest precedence of all operators, and the combination direction is “left to right”. (Comma operator: executes expressions sequentially and retrieves the value of the expression on the right.)

The general form of a comma expression is: expression 1, expression 2, expression 3… The expression of n

x=2*2,x*2;
console.log(x)  / / 4
Copy the code

7.4 void

The void operator returns undefined for any value. This operator is usually used to avoid printing values that should not be printed

Action 1: Return undefined

function tan(){
  return 33;
}
console.log(void tan());  // undefined
Copy the code

Function two: prevent unnecessary behavior. The void operator is useful when there is an A tag in the page, but the A tag is not meant to point to the page.

<a href='javascript:void(0)'>Point I'm not going to perform any behavior</a>
Copy the code

Flow statement

1. Loop statements

1.1 while

  1. Grammar:
while(conditional expression){looping block of code}Copy the code
  1. Process:
  • Loops the specified code block when the specified condition is true
  • Exits the body of the loop when the specified condition is false
  1. Features:
  • Conditions are checked and then the loop is executed. If conditions are not met, the loop is not executed once
  1. example
var i = 0;
while(i < 2) {console.log(i)
  i++;
}
/ / 0
/ / 1
Copy the code

1.2 the do… while

  1. Grammar:
do{looping block of code}while(conditional expression);Copy the code
  1. Process:
  • Execute the code block in the loop before judging
  • If the value of the expression is true, the code block is iterated
  • If the expression is false, exit the body of the loop
  1. Features:
  • The loop body is executed first, and then the condition is judged. The code in the loop body is executed at least once
  1. example
var i = 0;
do{
  console.log(i)
  i++;
}while(i < 2)
/ / 0
/ / 1
Copy the code

1.3 the for

  1. Grammar:
for(Loop variable = initial value; Cyclic conditions; Increment/decrement counter){code block for loop execution}Copy the code
  1. Process:
  • The return value is determined by comparing the initial value of the loop variable with the loop condition
  • If true is returned, the body of the loop is executed
  • After the execution, the increment/decrement cloud calculation is performed
  • Compare the result of the operation with the cyclic condition
  • If the return value is true, execution continues, and false exits the loop
  1. example
for(var i = 0; i <2; i++){console.log(i)
}
/ / 0
/ / 1
Copy the code

1.4 the for… in

  1. Grammar:
forDeclare variablesinObject){code block}Copy the code

The order of the attributes in the loop is unpredictable, and the value of the object cannot be null or undefined

  1. example
var arr= ['a'.'b'.'c'];
for(var x in arr ){
  console.log(arr[x]);
}
// a
// b
// c
Copy the code

2. Jump statements

2.1 the return

Terminates the loop body and returns a value

2.2 break

Terminates the entire loop, no longer making any judgments, only for loops or switches.

2.3 the continue

The continue statement interrupts the iteration in the loop, if the specified condition occurs, and continues to the next iteration in the loop. (i.e., end the loop and decide whether to execute the next loop)

3. Conditional statement

3.1 the if

  1. Grammar:
ifConditional expression1) {code block1
}else ifConditional expression2) {code block2
}else{code block3
}
Copy the code
  1. Process:
  • Check condition 1, if the return value is true, execute block 1
  • If the return value of condition 1 is false, the block is skipped and condition expression 2 is tested
  • If all expressions are false, the statement following else is executed
  1. example
var a = 1
var b = 2
if(a > b){
  console.log("true")}else{
  console.log("false")}// false
Copy the code

3.2 the switch

  1. Grammar:
switch(conditional expression){caseThe label1: the code block1;
    break; ... ...default: code block n; }Copy the code
  1. Process:
  • Evaluates the value of the expression and compares it with each label
  • If a matching tag is found, the following code block is executed
  • If no matching label is found, the code block following default is executed directly
  1. example
var day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "On Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "On Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case  6:
    day = "Saturday";
}
console.log("Today is" + day)

// Suppose new Date().getday () is 5
// Today is Friday
Copy the code

4. Exception handling statements

4.1 throw

Actively throwing an exception

4.2 the try

Specifies the code block to work with

4.3 catch

Catch exceptions

4.4 the finally

Post processing

An array of

1. Create a method

Array length is elastic and can be freely scaled; Array subscripts start at 0 and array elements can be added to objects

1. An empty array

var Obj = new Array(a);Copy the code

2. Specify the length array

var Obj = new Array( Size );
Copy the code

3. Specify an array of elements

var Obj = new Array(element1Elements,2Elements,3. , element N);Copy the code

4. One dimensional array

varObj = [element1Elements,2Elements,3. N], elements;Copy the code

5. Multidimensional arrays

var Obj = new Array[Array sequence1],[array sequence2],[array sequence3],... ,[array N]);Copy the code

2. Array properties

2.1 the constructor

The constructor property returns the object’s constructor

2.2 length

Length returns the length of the array

2.3 the prototype

Prototype extends the array definition by adding properties and methods

3. Go through the number groups

3.1 Using the For Loop

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

3.2 used for… in

var arr = ['a'.'b'.'c'];
for(i in arr){
  console.log(arr[i])
}
// a
// b
// c
Copy the code

3.3 use the forEach

var arr = ['a'.'b'.'c'];
arr.forEach(function(item) {
  console.log(item);
});
// a
// b
// c
Copy the code

4. Array methods

methods describe
concat() Joins two or more arrays and returns the result.
join() Put all the elements of an array into a string. Elements are separated by the specified delimiter.
pop() Removes and returns the last element of the array
push() Adds one or more elements to the end of the array and returns the new length.
reverse() Reverses the order of the elements in an array.
shift() Removes and returns the first element of the array
slice() Returns the selected element from an existing array
sort() Sort the elements of an array
splice() Removes the element and adds a new element to the array.
toSource() Returns the source code for this object.
toString() Converts an array to a string and returns the result.
toLocaleString() Converts an array to a local array and returns the result.
unshift() Adds one or more elements to the beginning of the array and returns the new length.
valueOf() Returns the original value of an array object

4.1 the concat ()

Joins two or more arrays and returns the result.

grammar

arrayObject.concat(arrayX,arrayX,...... ,arrayX)

example

var a = [1.2.3];
var b = a.concat(4.5)
console.log(b)
/ / [1, 2, 3, 4, 5]
Copy the code

4.2 the join ()

Put all the elements of an array into a string. Elements are separated by the specified delimiter.

grammar

arrayObject.join(separator)

example

var a = [1.2.3];
var b = a.join(",")
console.log(b)
/ / 1, 2, 3
Copy the code

4.3 pop ()

Removes and returns the last element of the array

The pop() method removes the last element of the arrayObject, reduces the array length by one, and returns the value of the element it removed. If the array is already empty, pop() does not change the array and returns undefined.

grammar

arrayObject.pop()

example

var a = [1.2.3];
var b = a.pop()
console.log(b)  / / 3
console.log(a)  / / [1, 2]
Copy the code

4.4 push ()

Adds one or more elements to the end of the array and returns the new length.

The push() method adds its arguments sequentially to the end of the arrayObject. It modifies the arrayObject directly, rather than creating a new array. The push() and pop() methods use the in-and-out functionality provided by arrays.

PS: This method changes the length of the array.

grammar

arrayObject.push(newelement1,newelement2,.... ,newelementX)

example

var a = [1.2.3];
var b = a.push(4)
console.log(b)  / / 4
console.log(a)  / / [1, 2, 3, 4]
Copy the code

4.5 reverse ()

Reverses the order of the elements in an array.

PS: This method changes the original array and does not create a new one.

grammar

arrayObject.reverse()

example

var a = [1.2.3];
var b = a.reverse()
console.log(b)  / / 3, 2, 1
console.log(a)  / / 3, 2, 1
Copy the code

4.6 the shift ()

Removes and returns the first element of the array

If the array is empty, the shift() method does nothing and returns undefined. Note that this method does not create a new array, but modifies the existing arrayObject directly.

PS: This method changes the length of the array.

grammar

arrayObject.shift()

example

var a = [1.2.3];
var b = a.shift()
console.log(b)  / / 1
console.log(a)  / / [2, 3]
Copy the code

4.7 slice ()

Returns the selected element from an existing array

PS: This method does not modify the array, but returns a subarray. If you want to delete an element from an Array, use the array.splice () method. You can use negative values to pick elements from the end of the array. If end is not specified, the slice() method selects all elements from start to the end of the array.

grammar

arrayObject.slice(start,end)

example

var a = [1.2.3];
var b = a.slice(1.2)
console.log(b)  / / [2]
console.log(a)  / / [1, 2, 3]
Copy the code

4.8 the sort ()

Sort the elements of an array

If this method is called without arguments, the elements in the array are sorted alphabetically, or more precisely, by character encoding. To do this, you first convert the elements of the array to strings, if necessary, for comparison.

grammar

arrayObject.sort(sortby)

example

var a = ['c'.'d'.'a'.'f'];
a.sort()
console.log(a)  // ["a", "c", "d", "f"]
Copy the code

4.9 splice ()

Removes the element and adds a new element to the array.

The splice() method removes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the argument list.

If an element is deleted from an arrayObject, an array containing the deleted element is returned.

PS: Note that the splice() method is different from the slice() method, which modifies the array directly.

grammar

arrayObject.splice(index,howmany,item1,..... ,itemX)

example

var a = [1.2.3];
var b = a.splice(1.2)
console.log(b)  / / [2, 3]
console.log(a)  / / [1]
Copy the code

4.10 toSource ()

Returns the source code for this object.

The original value is inherited by all objects derived from the Array object.

The toSource() method is usually called automatically in the background by JavaScript and does not appear explicitly in the code.

grammar

object.toSource()

example

function employee(name,sex,born){
  this.name=name;
  this.sex=sex;
  this.born=born;
}
var bill = new employee("miluluyo"."girl".1997);
document.write(bill.toSource());
//({name:"miluluyo", sex:"girl", born:1997}) 
Copy the code

4.11 the toString ()

Converts an array to a string and returns the result.

JavaScript calls this method to automatically convert an array to a string when it is used in a string environment. In some cases, however, you need to call this method explicitly.

grammar

arrayObject.toString()

example

var a = [1.2.3];
var b = a.toString()
console.log(b)  / / 1, 2, 3
console.log(a)  / / [1, 2, 3]
Copy the code

4.12 toLocaleString ()

Converts an array to a local array and returns the result.

The toLocaleString() method for each array element is called first, and the resulting strings are concatenated using locale-specific delimiters to form a single string.

grammar

arrayObject.toLocaleString()

example

var a = [1.2.3];
var b = a.toLocaleString()
console.log(b)  / / 1, 2, 3
console.log(a)  / / [1, 2, 3]
Copy the code

4.13 the unshift ()

Adds one or more elements to the beginning of the array and returns the new length.

The unshift() method inserts its arguments into the head of the arrayObject and moves the existing elements sequentially to the higher subscript to leave space. The first argument to the method will be the new element 0 of the array, if there is a second argument, it will be the new element 1, and so on.

The unshift() method does not create a new creation, but modifies the existing array directly. The unshift() method does not work correctly in Internet Explorer!

grammar

arrayObject.unshift(newelement1,newelement2,.... ,newelementX)

example

var a = [1.2.3];
var b = a.unshift(0.4.5)
console.log(b)  / / 6
console.log(a)  / /,4,5,1,2,3 [0]
Copy the code

4.14 the valueOf ()

Returns the original value of an array object

The original value is inherited by all objects derived from the Array object.

The valueOf() method is usually called automatically in the background by JavaScript and does not appear explicitly in the code.

grammar

arrayObject.valueOf()

example

var boo = new Boolean(false)
document.write(boo.valueOf())
// false
Copy the code

function

1. Define methods

1. Static methods

functionThe function name ([Virtual parameter list]){function body; [return[Function return value;] ]}Copy the code

2. Dynamic anonymous methods

varThe function name =new function(["Virtual parameter list"]."Function body")
Copy the code

3. Direct measurement method

The function name =function([Virtual parameter list]){function body; }Copy the code

2. Invoke the method

2.1 Direct Call

Function name (argument list)Copy the code

2.2 Called in link

<a href="Javascript: Function name ()">A label</a>
Copy the code

2.3 Called in an Event

Event type ="Function name ()"
Copy the code

2.4 Recursive invocation

Calls the function itself from within the function body

functionThe function name (){code function name (); }Copy the code

Method 3.

apply

Call a function as a method on an object, passing the arguments to the method as an array

grammar

function.apply(thisObj,[arg1,arg2,....argN])

call

Calls a function as a method of an object, passing the specified arguments to the method

grammar

function.call(thisObj, arg1,arg2,... argN)

var foo = {
  value: 1
};
function bar() {
  console.log(this.value);
}
bar.call(foo); / / 1
// Call changes the direction of this to foo
// the bar function executes
Copy the code

toString

Returns a string representation of the function

4. The arguments object

Arguments is an array-like object corresponding to the arguments passed to the function.

Arguments objects are local variables available in all (non-arrow) functions.

attribute

4.1 length

Gets the length of the function argument

4.2 the arguments. The callee

Returns the function to which you are currently pointing

Cannot be used in strict mode.

function test() {
  console.log(arguments.callee) 
}
test();  //fn test
Copy the code

4.3 caler

Returns the name of the function calling the currently executing function

5. Function parameters

The parameter types

5.1 parameter

Defines the arguments used when the function is called and receives the arguments passed when the function is called

5.2 the arguments

The actual argument passed to the function when it is called

features

  1. There is no limit to the number of parameters;

Argument < parameter: extra parameter = undefined

Argument > parameter: redundant parameters are ignored

  1. There is no restriction on the data type of the parameter;

  2. Access the arguments array via the Arguments object

  3. Parameters are always passed by value

** Basic type: ** Pass value

** Reference type: ** address

6. Pointer identifier

6.1 this

Points to the current operation object

6.2 the callee

Points to the function that the parameter collection belongs to

6.3 the prototype

Points to the prototype object attached to the function

6.4 the constructor

Points to the constructor that created the object

7. Arrow function (ES6)

And ordinary functions

  1. Do not bind this, the arguments
  2. More simplified code syntax.

This is not binding

The arrow function’s this is always undefined this

Do not bind the arguments

You can’t get what you want if you use arguments in arrow functions.

function(){
    console.log('hello')}// Write the arrow function as follows:
()=> conosle.log('hello')
Copy the code

8. Closure

JavaScript variables are local or global scoped.

Global variables can be made local (private) through closures.

Closures are a mechanism for protecting private variables from outside interference by forming private scopes during function execution.

Intuitively speaking is to form an undestroyed stack environment.

var add = (function () {
    var counter = 0;
    return function () {return counter += 1; }}) ();console.log(add());  / / 1
console.log(add());  / / 2
console.log(add());  / / 3
Copy the code

The assignment of the variable add is the return value of the self-calling function.

This self-calling function is run only once. It sets the counter to zero (0) and returns the function expression.

So add becomes a function. The “cool” part is its ability to access counters in the parent scope.

This is called a JavaScript closure. It makes it possible for functions to have “private” variables.

Counters are protected by the scope of this anonymous function and can only be modified using the add function.

Closures are functions that have access to the parent scope, even after the parent function is closed.

String function

1. Find the method

1.1 String Methods

chartAt()

ChartAt () returns the NTH character in the string

chartCodeAt()

ChartCodeAt () returns the code for the NTH character in the string

fromCharCode()

FromCharCode () creates a string based on the character encoding

Relationship between

Common features of charAt and charCodeAt: Searches for specified characters based on subscripts. CharCodeAt and fromCharCode: operate in reverse order

1.2 Location Method

indexOf()

IndexOf () retrieves a string from front to back to see if it contains the specified string

lastIndexOf()

Retrieves a string from back to forward to see if it contains the specified string

1.3 Matching Method

match()

Match () finds a match for one or more regular expressions

search()

Search () retrieves the string in the string that matches the regular expression

replace()

Replace () replaces a string that matches the regular expression

split()

Split () splits the string into multiple strings based on the specified delimiter and returns an array

2. Operation method

2.1 Splicing Method

concat()

Concatenates the specified string to the end of this string

grammar

string.concat(value..)

String str = "abc";
str = str.concat("123");
System.out.println(str);//abc123
Copy the code

2.2 Obtaining Method

Intercepts a string by subscript

slice()

Slice () is added to the character length

substring()

Substring () converts to 0

Intercepts the string by length

Substr () The number of characters returned by substr()

2.3 Blank Handling

Trim Clears prefix and suffix Spaces

TimLeft Clears leading Spaces

TrimRight clears suffix Spaces

2.4 Comparison Method

LocalCompare () compares two strings in a locally specific order

3. Coding method

Escape (), unescape()

EncodeURI (), decodeURI()

4. Transform methods

4.1 Case Conversion

Uppercase toUpperCase(), toLocaleUpperCase()

Convert toLowerCase toLowerCase(), toLocaleLowerCase()

URI component encoding and decoding encodeURIComponent(), decodeURIComponent()

Regular expression

0. Regular expressions

Regular Expression (often abbreviated as regex, regexp, or RE) uses a single string to describe and match a series of string search patterns that conform to a syntactic rule.

1. :

literal

varThe variable name =/ expression /Pattern modifierCopy the code

The constructor

varThe variable name =new RegExp("Expression"."Pattern modifier")
Copy the code

2. The expression

Single character and number

coding Break down
. Matches any character except newline
[a-z0-9] Matches any character in square brackets
[^a-z0-9] Matches any character not in square brackets
\d Match the Numbers
\D Match non-numbers
\w Match the letter
\W Match non-letter

White space characters

coding Break down
\ 0 Matching null characters
\b Match space character
\f Matches the feed character
\n Matches a newline character
\r Match carriage return
\s Matches whitespace characters, Spaces, tabs, or newlines
\S Matches non-whitespace characters
\t Matches TAB characters

locator

coding Break down
^ The beginning of a line matching
$ The end of each line matching
\A Matches only the beginning of the string
\b Matches word boundaries, words are invalid inside []
\B Matches non-word boundaries
\G Matches the start of the current search
\Z Matches the end of the string or line
\z Matches only at the end of the string

qualifiers

coding Break down
x? Matches 0 or 1 X
x* Matches zero or any number of x’s
x+ Matches at least one X
x{m,n} Match at least m and at most N x’s

grouping

coding Break down
(? :x) Matches x but does not record the match
x(? =y) Matches x when x is followed by y
x(? ! y) Matches x when x is not y

reference

coding Break down
\ 1… 9 \
1 1…
Returns nine recently saved parts found during pattern matching

Or lost

coding Break down
x` y

3. Schema modifiers

coding Break down
g Global mode, applied to all strings
i Case sensitive pattern
m Multi-line matching pattern

4. The attribute

Instance attributes

coding Break down
global Checks whether the G flag is set
ignoreCase Checks whether the I flag is set
multiline Checks if the M flag is set
lastIndex Begins retrieving the character position of the next match
source Returns a string representation of the regular expression
lastIndex Returns the start of the next successful match in the searched string

Constructor properties

coding code Break down
The $_ input Returns the string of the last match
$& lastMatch Returns the last match
+ $ lastParen Returns the capture group that was last matched
$` leftContext Returns the characters in the searched string from the beginning of the string to the position before the final match
$’ rightContext Returns the characters in the searched string from the last matching position to the end of the string
$* multiline Checks if the expression matches m in a multi-line pattern

Method 5.

Instance methods

exec

Exec performs a match retrieval in a string, returning an array of results

Derived attributes

Index Position of the match in the string input String length that applies the regular expression returns the number of elements in the array

test

Test tests pattern matches in a string, returning true or false

String method

coding Break down
match Finds a match for one or more regular expressions
replace Replaces the substring that matches the regular expression
search Retrieves the value that matches the regular expression
split Splits a string into an array of strings

Basic DOM operations

0. DOM

All elements of a JavaScript HTML document are accessible through the HTML DOM.

When a web page is loaded, the browser creates the Document Object Model of the page.

1. Obtain the node

document

coding grammar
getElementById Document. The getElementById (element ID)
getElementByName Document. GetElementByName (element name)
getElementByTagName Document. The getElementByTagName (element tag)

Node pointer

coding grammar function
firstChild The parent node. FirstChild Gets the first child node of the element
lastChild The parent node. LastChild Gets the last child node of the element
childNodes The parent node..childnodes Gets the list of children of the element
previousSibling PreviousSibling node Gets the previous node of a known node
nextSibling Sibling node nextSibling Gets the next node of a known node
parentNode Child nodes. ParentNode Gets the parent of a known node

2. Perform node operations

Create a node

coding grammar function
createElement Document.createelement (Element tag) Creating element nodes
createAttribute Document.createattribute (Element attribute) Creating a property node
createTextNode Document.createtextnode (Text content) Creating a text node

Insert the node

coding grammar function
appendChild AppendChild (new node added) Adds a new child node to the end of the node’s child node list
insertBefore InsertBefore (new node to add, known child nodes) Inserts a new child node before a known child node

Replace the node

coding grammar function
replaceChild ReplaceChild (new element to be inserted, old element to be replaced) Replace one child node with another

Copy the node

coding grammar function
choneNode The node that needs to be copied cloneNode(true/false) Creates a copy of the specified node

True: copies the current node and all its children false: copies only the current node

Remove nodes

coding grammar function
removeChild RemoveChild (node to remove) Delete the specified node

3. Attribute operations

Retrieve attributes

coding grammar function
getAttribute Element node. GetAttribute Gets the attribute value of the specified attribute in the element node

Set properties

coding grammar function
setAttribute Element node. SetAttribute (attribute name, attribute value) Creates or changes the attributes of the element node

Delete the properties

coding grammar function
removeAttribute Element node. RemoveAttribute Deletes the specified attribute from the element

4. Text operations

coding function
insertData(offset,String) Inserts a string from the position specified by offset
appendData(string) Insert string at the end of the text node
deleteDate(offset,count) Delete count characters from offset
replaceData(off,count,string) Replace the count character from off with a string
splitData(offset) Splits the text node into two nodes from offset
substring(offset,count) Return count of nodes starting from offset

The Window object

1. The Navigator object

coding Break down
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion The platform and version information of the browser is displayed
cookieEnabled Returns a Boolean value indicating whether cookies are enabled in the browser
platform Return to the operating system platform where the browser is running
userAgent Returns the value of the user-Agent header of the server sent by the client

2. Screen Display object

coding Break down
availHeight Returns the available height of the display screen
availWidth Returns the available width of the display screen
height Returns the pixel height of the screen
width Returns the pixel width of the screen
colorDepth Returns the number of bits of screen color

3. History History object

coding Break down
back() Returns the previous URL
forward() Returns the next URL
go() Returns a specific page

4. Location Location object

attribute

coding Break down
hash Sets or returns the URL starting with the hash sign (#)
host Sets or returns the hostname and port number of the current URL
hostname Sets or returns the host name of the current URL
href Sets or returns the full URL
pathname Sets or returns the path portion of the current URL
port Sets or returns the port number of the current URL
protocol Sets or returns the protocol for the current URL
search Sets or returns from question mark (?) Start the URL

methods

coding Break down
assign(URL) Loading a new document
reload() Reload the current page
replace(newURL) Replace the current document with the new document

5. Document Document object

A collection of

coding Break down
anchors[] Array of trace point objects
images[] Image object array
links[] Join object array
forms[] Form object array

attribute

coding Break down
cookie Sets or returns all cookies associated with the current document
domain Returns the domain name of the current document
referrer Returns the URL of the document that loads the current document
title Returns the title of the current document
URL Returns the URL of the current document

methods

coding Break down
open() Open a new document and erase the contents of the old document
close() Close the document output stream
write() Appends text to the current document
writeIn() As with write(), in<pre>Line breaks are appended to

6. Window control

coding grammar Break down
moveBy MoveBy (horizontal displacement, vertical displacement) Moves the specified window according to the given pixel parameter
moveTo moveTo(x,y) Moves the window to the specified coordinates (x,y)
resizeBy ResizeBy (horizontal, vertical) Changes the current window to the specified size (x,y)

When the value of x and y is greater than 0, it is enlarged

The value of x and y is smaller than 0
resizeTo ResizeTo (horizontal width, vertical width) Change the current window size to (x,y), where x and y are the width and height, respectively
scrollBy ScrollBy (horizontal displacement, vertical displacement) Scroll the contents of the window by the given amount of displacement

If the parameter is an integer, scroll forward; otherwise, scroll backward
scrollTo scrollTo(x,y) Scrolls the contents of a window to the specified position

7. Focus control

coding Break down
focus Get focus
blur Out of focus

8. Open and close the window

open

coding grammar Break down
open Open (“URL”,” window name “,” window style “) Opens a new window and loads a web page at the specified URL

Window style

coding grammar Break down
location yes/no Whether to display the address bar
menubar yes/no Whether to display the menu bar
resizable yes/no Whether the window can be resized
scrollbars yes/no Whether scroll bars are allowed
status yes/no Whether to display the status bar
toolbar yes/no Whether to display toolbar

close

coding grammar Break down
close close() Automatically closes the browser window

9. The timer

coding grammar Break down
setTimeout SetTimeout (execute code in milliseconds) Automatically executes the function code when the specified number of milliseconds is reached
clearTimeout ClearTimeout (timer) Cancels the timer set by setTimeout()
setInterval SetInterval (code executed repeatedly, milliseconds) Repeat the execution of the functional code at the specified period
clerInterval clearInterval Cancel the interval set by setInterval()

The dialog box

coding grammar Break down
alert Alert (” prompt string “) A warning dialog box is displayed, in which the warning string text is displayed
confirm Confirm (” confirm string “) Displays a confirmation box in which the prompt string is displayed

This method returns true when the user clicks OK and false when the user clicks Cancel
prompt Prompt (” prompt string “,” default text “) Displays an input box in which the prompt string is displayed

Displays default text in the input text box and waits for user input

The input string is returned when the user clicks OK, and null is returned when the user clicks Cancel

11. The attribute

The status bar

coding Break down
defaultStatus Change the default display of the browser status bar
status Temporarily change the browser status bar display

The window position

IE

ScreeTop screeTop screeTop screeTop screeTop screeTop screeTop screeTop Declares the number of pixels that the current document scrolls down

! IE

ScreenX: screenY: screenY: Y: screenY: Y: pageXOffset: how many pixels have been scrolled to the right of the current document

FF

OuterHeight returns the outerHeight of the window. OuterWidth returns the outerWidth of the window

Other attributes

coding Break down
opener Can realize the communication between the form and the domain name

One form contains the opener of another form
closed Returns true when the current window is closed
name Sets or returns the name of the window
self Returns a reference to the current window

JS object

1. The javascript object

Everything in JavaScript is an object: strings, numbers, arrays, dates, and so on.

In JavaScript, objects are data (variables) with properties and methods.

Properties and methods

Properties are values associated with an object. A method is an action that can be performed on an object. In object-oriented languages, properties and methods are often referred to as members of an object.

2. Create javascript objects

Method one:

let Person = new Object(a);// Declare an empty object
Copy the code

Method 2:

let Person = {};   // Declare an empty object
Copy the code

3. Object properties and object methods

JavaScript Properties Properties refer to values associated with JavaScript objects.

JavaScript objects are unordered collections of properties.

Properties can generally be modified, added, and removed, but some properties are read-only.

Access the syntax objectName.propertyName

JavaScript method

Methods are functions stored as properties of objects.

Objectname.methodname ()

let Person = new Object(a); Person.name ="Moose Luyo."  // Set object properties
Person.age = 22
Person.getDate = function(){  // Set object methods
  return new Date(a); }console.log(Person) // {name: "eluyo ", age: "22"}

console.log(Person.name)  // Elk Luyo // access object properties
console.log(Person.getDate()) // Output the current time // access object methods

delete Person.age  // Delete keyword deletes attributes from the object
Copy the code

PS: the name of the object, which is case-sensitive.

4. Object accessors (GET, set)

Why use getters and setters?

  • It provides a more concise syntax
  • It allows properties and methods to have the same syntax
  • It ensures better data quality
  • Good for background work

JavaScript Getter (get keywords)

var Person = {
  name: "Moose Luyo.".age : 22.get lang() {
    return this.age; }};console.log(Person.lang)  / / 22
Copy the code

JavaScript setters (set keywords)

var Person = {
  name: "Moose Luyo.".age : 22.set lang(lang) {
    this.age = lang; }};// Use setters to set object properties:
Person.lang = 3
console.log(Person.age)  / / 3
Copy the code

5. Object constructor

function Person(name,age){
  this.name = name;
  this.age = age;
}
Copy the code

The Person() function is the object constructor function.

Calling the constructor function with the new keyword creates an object of the same type:

var me = new Person("Moose Luyo.".22);
Copy the code

This keyword

In JavaScript, something called this is the “owner” of the code.

The value of this, when used within an object, is the object itself.

In the constructor function, this has no value. It’s a substitute for the new object. When a new object is created, the value of this becomes the new object.

Note that this is not a variable. It’s the key word. You cannot change the value of this.

6. JavaScript object prototype

Prototype inheritance

All JavaScript objects inherit properties and methods from stereotypes.

  • The Date object inherits from date.prototype.
  • Array objects inherit from array. prototype.
  • The Person object inherits from Person.prototype.
  • Object. Prototype is at the top of the prototype inheritance chain:
  • Date objects, array objects, and Person objects all inherit from Object.Prototype.

The prototype property

The JavaScript Prototype property allows you to add new properties, methods to the object constructor

function Person(name,age){
  this.name = name;
  this.age = age;
}
Person.prototype.github = "https://github.com/miluluyo";
Copy the code

7. ES5 object methods

code Break down
Object.defineProperty(object, property, descriptor) Add or change object properties
Object.defineProperties(object, descriptors) Add or change multiple object properties
Object.getOwnPropertyDescriptor(object, property) To access attributes
Object.getOwnPropertyNames(object) Returns all properties as an array
Object.keys(object) Returns all enumerable properties as an array
Object.getPrototypeOf(object) Access to the prototype
Object.preventExtensions(object) Prevents adding attributes to objects
Object.isExtensible(object) Returns true if attributes can be added to an object
Object.seal(object) Preventing changes to object properties (rather than values)
Object.isSealed(object) Returns true if the object is sealed
Object.freeze(object) Prevents any changes to the object
Object.isFrozen(object) Returns true if the object is frozen

7. The prototype of inheritance

grammar

Subclasses. The prototype =newThe parent class ()Copy the code

All JavaScript objects inherit properties and methods from a Prototype object.

Points to an object that is the prototype of the instance created by formally calling the constructor

proto

__proto__ This is a property that every javascript object (except null) has, and this property points to the object’s prototype

8. Number object

coding Break down
toExponential() Converts the value of an object to an exponential notation.
toFixed() The Number can be rounded to a specified decimal Number.
toPrecision() Method converts an object to an exponential notation when its value exceeds a specified number of digits.
toString() Converts a logical value to a string and returns the result.
valueOf() Returns the original value of a Boolean object.

9. Math object

Perform common arithmetic tasks.

coding Break down
abs(x) Return the absolute value of x.
acos(x) Returns the inverse cosine of x.
asin(x) Returns the arcsine of x.
atan(x) Returns the arctangent of x between -pi /2 and PI/2 radians.
atan2(y,x) Returns the Angle from the X-axis to the point (x,y) between -pi /2 and PI/2 radians.
ceil(x) The logarithm is rounded up.
cos(x) Returns the cosine of the number.
exp(x) Returns the index of Ex.
floor(x) Round down x.
log(x) The natural logarithm of the number returned (base e).
max(x,y,z,… ,n) Return the x, y, z,… , the highest value of n.
min(x,y,z,… ,n) Return the x, y, z,… The lowest value of n.
pow(x,y) Return x to the y power.
random() Returns a random number between 0 and 1.
round(x) Round off.
sin(x) Return the sine of a number.
sqrt(x) Returns the square root of the number.
tan(x) Return the tangent of the Angle.

JSON

1. JSON

  • JSON stands for JavaScript Object Notation.
  • JSON is a lightweight data interchange format
  • JSON is self-descriptive and easy to understand
  • JSON is language independent *

JSON is a format for storing and transferring data.

JSON is often used when data is sent from a server to a web page

Exchange data

When data is exchanged between the browser and the server, it can only be text.

JSON is text, and we can convert any JavaScript object into JSON and send it to the server.

We can also convert any JSON we receive from the server into JavaScript objects.

In this way, we can treat data as JavaScript objects without complicated parsing and translation.

JSON.parse()

Strings written in JSON format are converted to native JavaScript objects

JSON.parse()  
Copy the code

JSON.stringify()

Json.stringify () converts JavaScript objects to strings.

var obj = { name:"Moose Luyo.".age:22};
JSON.stringify(obj)  
Copy the code

2. JSONP

JSONP is a way to transfer JSON data without considering cross-domain issues.

JSONP does not use XMLHttpRequest objects.

JSONP uses the

JSONP is JSON with Padding.

Requesting files from another domain can cause problems due to cross-domain policy.

Requesting external scripts from another domain does not have this problem.

JSONP takes advantage of this and uses script tags instead of XMLHttpRequest objects.

Using script tags to bypass the same-origin policy and get data like this, jSONPCallback is the callback method that exists on the page, and the parameters are the desired JSON.

It only supports GET requests and does not support other types of HTTP requests such as POST. It only supports cross-domain HTTP requests and does not solve the problem of how to make JavaScript calls between two pages in different domains

Cookie

1. Cookie

Cookie is actually a short piece of text information. The client requests the server. If the server needs to record the user status, it issues a Cookie to the client browser using response. The client will save the Cookie, when the browser requests the website, the browser will submit the requested URL together with the Cookie to the server, the server checks the Cookie, in order to identify the user status, the server can also modify the content of the Cookie according to the demand

2. The advantages

  1. Extremely high scalability and availability

You can control the size of session objects stored in cookies;

Through encryption and secure transmission technology (SSL), reduce the possibility of Cookie cracking;

Only store insensitive data in cookies, there will be no significant loss if stolen;

Control the Cookie’s lifetime so that it will not be valid forever, and the thief may get an expired Cookie;

Text-based lightweight structure;

Cookies are stored on the client and read by the server after being sent;

3. The shortcomings

  1. Limits on the number and length of cookies

Each domain can have a maximum of 20 cookies. The length of each cookie cannot exceed 4KB; otherwise, the cookie will be truncated.

  1. security

Cookies can be intercepted or tampered with. If the Cookie is intercepted, that person can get all session information

  1. Some states cannot be saved on the client side

Example: To prevent repeated submission of forms, save the counter on the server side, if the counter is saved on the client side, it is useless.

Extension 4.

The difference between cookies and sessions

  1. Cookie data == Client browser session data == server

  2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, session should be used

  3. Session will be stored on the server for a certain period of time. When the number of accesses increases, the server performance will be occupied. Therefore, cookies should be used to reduce the server performance

  4. Individual Cookie data cannot exceed 4K, and many browsers limit the number of cookies stored on a site to 20

Advice:

  • Important information such as login information is stored in the session
  • Other information can be placed in cookies if you want to keep it