0 is introduced

0.1 ECMAScript

Version 5 of ECMA-262 is the first stable release of JS, supported by various browser vendors.

  • grammar
  • type
  • statements
  • keywords
  • Reserved words
  • The operator
  • object

0.2 the DOM

The Document Object Model is an API for XML but extended for HTML. DOM maps the entire page to a multi-level node structure. Each component of an HTML or XML page is a node of some type, which in turn contains a different type of data. Document Object Model, which provides properties and methods that allow us to manipulate elements on a page

0.3 BOM

In principle, the BOM only deals with browser Windows and frames, but the following JS extensions for browsers are also considered part of the BOM. The Browser Object Model provides properties and methods that allow you to manipulate the browser.

1 the import JS

1.1 Three common imports

1.1.1 Importing JS in line (Caution: Unsafe)

<div onclick="alert('hello world')"></div>
Copy the code

1.1.2 embedded

<script>
	alert('hello world')
</script>
Copy the code

1.1.3 outside the chain

// Create a new js file<script src="./js/demo.js"></script>

// or

<script src="./js/demo.js" type="text/javascript"></script>
Copy the code

1.2 The embedded and external chain cannot be operated at the same time

An inline import and an external import cannot be combined, and all code written in a script block will not be executed if it is currently an external import.

<script src="./js/demo.js">
  alert('hello world')
</script>
Copy the code

1.3 Position Write a position

We typically put CSS at the top of the body and JS at the end (convention quick spec)

But what happens if you put it in front of the tag?

Perform the operation after the page has loaded all resources

In js

window.onload=function(){}Copy the code

In jq

$(document).ready(function(){})window.addEventListener('load'.function(){},false);

/ / below ie8

window.attachEvent('onreadystatechange'.function(){})Copy the code

2 Common output modes of JS

2.1. Popup output

2.1.1 alert.

  • Pop up a prompt box in the browser (provide ok button, click OK popup disappears)
  • With the alert popover message, the prompt is converted to a string (toSring is called).
alert(1)
alert({name:'wjw'}) //=> '[object Object]'
alert([13.14]) / / = > '12, 13
Copy the code

2.1.2 confirm

  • Added actions for users to select based on Alert (provides two buttons: OK and cancel)
  • When the user clicks OK, we receive true, and when the user clicks Cancel, we receive false, and then we can work with the result
var wjw = confirm("are you sure");
alert(wjw);
Copy the code

2.1.3 prompt

    • Add the effect that allows the user to add input to confirm
    • If the user clicks on the cancel button, we get null, and if the user clicks on the OK button, we get the input from the user
    • In real projects, it is common to use secondary wrapped popovers instead of such popovers
var flag = prompt("are you sure");

alert(flag)
Copy the code

2.2 Console Output

Console output, convenient development and debugging

2.2.1 the console

  • In console output, advantage does not convert the data type, output data in any format can be
console.log({name:'wjw'});

console.dir() // More verbose than the log output
console.table // Display the JSON data as a table
Copy the code

3 JS Defines the value

Syntax ECMAScript’s syntax borrows heavily from C and other C-like languages such as Perl and Java. Case sensitive

3.1 annotations

// Single-line comment

/* * This is a multi-line * (block-level) comment */
Copy the code

3.2 Strict Mode

Strict mode ES5 introduces the concept of strict mode, in which uncertain behavior in ES3 is handled and errors are thrown for unsafe operations. To enable strict mode throughout the script, add the following code at the top: this line of code looks like a string and does not assign any variables, but is actually a pragma that tells the supporting JavaScript engine to switch to strict mode. You can also specify that the function executes in strict mode by including this compilation instruction above the inside of the function:

function doSomething(){
 	"use strict";  / / the function body
}
Copy the code

3.3 Variables and constants

Variables can be constant and immutable

3.3.1 variable

  • A variable is just a meaningless name, and all it represents is the value it stores
  • Change the value of the num variable to 13.

Js method for defining variables

// var Variable name = value;

var num = 12;
var name = 'wjw'
Copy the code

3.3.1 constants

  • Any specific number is a constant. For example, 12 is a constant
  • With variable exhaustion, we set a constant (that is, a name) and store a value to it, but the stored value cannot be changed
const num = 12;
Copy the code

3.4 Naming conventions in JS

  • JS is case sensitive
var test = 'wjw';
var Test = 'wjh';
console.log(test);
/ / output test
Copy the code
  • Follow the international nomenclature “hump nomenclature”

The first word starts with a lowercase letter and every other meaningful word starts with a capital letter

var studentInfo; // Student information
// What you see is what you get
/ / example:

/* * info: init: Initlization initialization * add/insert/create add insert create * remove/rm/clear/del update to modify/delete delete * * get/query/select: * / query
Copy the code
  • You can use $($), _ (_), digits, and letters, but cannot start a name with a digit
var student_info;
var $xxx; //=> Generally, jq is used to obtain the value
var _xxx; //=> This usually means that the variable is a local or public variable
Copy the code
  • JS many words are special meaning, we these words, called keywords; It has no special meaning now, and may later serve as a key, which we call a reserved word; Keywords and reserved words can not be used to name;



4 JS data type

4.1 Data Types

4.1.1 Basic Data Types (Value Types)

  • The Number of digital
  • String String
    • All strings are enclosed in single quotes (there is no difference between odd and even)
  • Boolean Boolean
    • True false => The Boolean value has only two values
  • Null Null object pointer
  • Undefined undefined

4.1.2 Reference data types

  • {} Ordinary objects
  • [] array
  • / ^ $/ regular
  • .

4.1.3 Function Data type

  • funciotn fn (){}

4.2 Data Type Check

  • typeof
    • Operator used to detect data types
  • instanceod
    • Detects whether an instance belongs to this class
  • constructor
    • Gets the constructor for the current instance
  • Object prototype.toSting.call()
    • Gets information about the class to which the current instance belongs

2 typeof

The typeof operator is an operator used to detect the data typeof a given variable. Using the Typeof operator on a value may return one of the following strings:

"undefined"
"boolean"
"string"
"number"
"object" // If the value is an object or null "function"
Copy the code

4.3 Boolean value

Boolean()

  • Converts values of other data types to Boolean types
  • Only 0, Nan, null, and undefined are converted to Boolean false, while the rest are converted to true

The exclamation mark has a function in JS: take the inverse, first convert the value to a Boolean type, and then take the inverse

!!!!!

If an exclamation point is reversed twice, no operation has been performed, but a value of any other type has already been converted to a Boolean

4.4 the string

In JS, both single and double quotation marks enclose strings

12 - > number
'12' -> string
'[12, 10]' -> string
Copy the code

4.4.1 the toString ()

The first is to use the toString() method, which is present for almost every value. In most cases, the toString() method is called without passing an argument, but when the toString() method of a number is called, one argument can be passed: the cardinality of the output number. By default, the toString() method returns a string representation of a numeric value in decimal format. By passing the base, toString() can output binary, octal, hexadecimal, and so on.

var num = 10;
alert(num.toString());    10 "/ /"
alert(num.toString(2));  / / "1010"
alert(num.toString(8));  / / "12"
alert(num.toString(10));  10 "/ /"
alert(num.toString(16));  // "A"
Copy the code

Commonly used method

4.5 number number

NaN Typeof NaN -> number is added in 12.5 jS

var intNum = 55; Var octalNum1 = 070; // octal 56
var octalNum1 = 079; // Invalid octal value -- resolves to 79
var octalNum1 = 08; // Invalid octal value -- resolves to 8
var hexNum1 = 0xA;  // hexadecimal 10
var hexNum2 = 0x1F; // 31 in hex
Copy the code

Note that octal literals are not valid in strict mode, resulting in a throw error.

4.5.1 Numerical range

The smallest Number ECMAScript can represent is stored in number.min_value — in most browsers, this value is 5E-324; Can be Number.MAX_VALUE – in most browsers, this value is 1.7976931348623157e+308. If the result of a calculation is a value that exceeds the JavaScript value range, the value is automatically converted to Infinity, or -infinity if it is negative, or Infinity if it is positive. To determine if a number isFinite, use the isFinite() function.

4.5.2 of NaN

  • Not a numer: it is not a number but belongs to the number type
  • NaN == NaN: false, NaN is not equal to any other value

4.5.3 isNaN ()

  • Used to check whether the current value is a non-significant digit. If it is not a significant digit, the result is true, and if it is a significant digit, it is false
isNaN(0)   // ->false
isNaN(NaN) // ->true
Copy the code
  • When we use the isNaN test, the value detected is not of type number. The browser default values are converted to type number and then checked
isNaN('12') //->false
Copy the code

4.5.4 Number ()

  • Convert other data type values to values of type number
Number('12') / / - > 12
Number('12px') // ->NaN
// When the Number conversion is used, any non-valid numeric character in the string will result in NaN

Number(true) / / - > 1
Number(false) / / - > 0
Number(null) / / - > 0
Number(undefined) //->NaN


Copy the code
  • To convert a reference datatype to number, first convert the reference datatype to a string (toString), then convert the string to number
Number([]) / / -- > ""
Number([12]) / / - > 12
Number([12.13]) // -> 12,13 (, non-valid characters) -> NaN
Number({age:12}) // ->NaN
Number({}) // -> NaN
Copy the code

4.5.5 pareInt

  • The other data type values are converted to number, which is different from the number method when dealing with strings
Number('12px') // -> NaN
parseInt('12px') / / - > 12
Copy the code
  • Extraction rule: Search for valid numeric characters from left to right until it encounters non-valid numeric characters (regardless of whether there are any left on the back end)
parseInt('12px13') / / - > 12
Copy the code

4.5.6 Numerical conversion

The most common way to deal with integers is still parseInt(), which ignores the space before the character until it finds the first non-space character. If the first character is not a numeric character or a minus sign, parseInt() returns NaN; That is, converting an empty string with parseInt() returns NaN. If the first character is a numeric character, parseInt() continues parsing the second character until all subsequent characters are parsed or a non-numeric character is encountered. If a character starts with “0x” and is followed by a numeric character, it is resolved to a hexadecimal integer. A string that starts with “0” and is followed by a numeric character is interpreted as an 8-digit integer. Here are some examples:

var num1 = parseInt("1234blue");   / / 1234
var num2 = parseInt("");     // NaN
var num3 = parseInt("0xA");    // 10(hexadecimal)
var num4 = parseInt(22.5);   / / 22
var num5 = parseInt("70");     / / 70
var num6 = parseInt("0xf");    // 15(hexadecimal)
Copy the code

4.5.7 pareFloat

  • A decimal point can be recognized on the basis of pareInt
pareInt('12.5 px.) - >12
pareFloat('12.5 px.) - >12.5
Copy the code

4.6 null, and undefined

  • Null: No
  • Undefined: undefined
  • “” : empty string, no
  • 0: It can also be interpreted as none

4.6.1 The difference between an empty string and null

  • I went to plant trees
  • The empty string is a hole dug, but not planted with anything
  • Null is not even digging a hole
  • Empty strings open up memory addresses relative to null, costing a little bit of performance

4.6.2 Difference between null and undefined

  • In js, null is manually assigned to null, and we will assign specific values to it later
  • Undefined: completely unexpected

4.7 Object

An object in ECMAScript is simply a collection of data and functionality. Objects can be created by executing the new operator followed by the name of the object type to be created. By creating an instance of type Object and adding attributes and/or methods to it, you can create custom objects as follows:

var o = new Object(a);Copy the code

Each object is composed of zero to multiple sets of attribute names: attribute values, or groups of key-value pairs separated by commas

4.7.1 properties

That describes the characteristics of this object

var obj ={name:'wjw'.age:8};
Copy the code

4.7.2 access

The value or numeric format of an attribute name

obj.name
obj['name']
Copy the code

4.7.3 storage

Property values can be of any data type

  • Object name. Attribute name: Ignores single and double quotation marks for attribute names
  • Object name [attribute name] : Single and double quotation marks cannot be ignored
// What if the attribute name is a number
obj. 0Syntax does not support obj[0] / obj['0'] Both are supportedCopy the code

If the attribute name of the operation does not exist in the object, the result is undefined

obj.sex // ->undefined
Copy the code

4.7.4 Setting/Modification

The property name of an object cannot be repeated (unique). If it exists before, it is an operation to change the value of the property. If it does not exist, it is a new operation to set the property

obj.sex = 'male';
obj['age'] = 9;
Copy the code

Stating to delete

Fake delete: assign the property to NULL, but the property is still the object
obj.sex = null;
Copy the code
True delete: Removes the entire property from the object by force
delete obj.sex
Copy the code

4.8 Differences between basic data types and reference data types

JS is run in the browser (kernel engine), the browser will provide the environment for JS to live (provides the environment for JS code execution) => global scope window(global)

var a = 12;
var b = a; // Assign the value stored in A to B
b = 13;
console.log(a);

var n ={name:'wjh'};
var m = n;
m.name = 'wjw'
console.log(n.name)
Copy the code
  • Basic datatypes operate by value: When assigning a value to a basic datatype, you simply assign the value to a variable
  • Var n = {name:’ WJW ‘} var n = {name:’ WJW ‘}
    • Let’s create a variable n
    • The browser will first create a new storage control (memory control), the purpose is to store the contents of the object (key-value pair) respectively in this space, in order to facilitate the later find this space, the browser set an address for the space (hexadecimal).
    • Assigns the address of the space to the variable

4.9 Function Data type

Function data types also operate on reference addresses

Function: a method that has a function

// => create function:
functionThe function name (){
	//=> Function body: the specific JS code that implements a function
}
(if the function is created but not executed, the function has no meaning)
// Function name ()
Copy the code
function fn(){
	console.log(1+1);
}
fn; // => Outputs the function itself
fn(); // => execute the function.
Copy the code

Parameter: formal parameter (variable), function entry When we create a function to achieve a function, we find that some materials are not clear, only when the function is running, others pass to me, I know, at this time we need to set the entry, let the user when the implementation of the entry value to us

function fn(num1,num2){
	console.log(num1+num2)
}
// Arguments: The actual values passed to the function by the execution of the function are arguments
fn(1.2);
fn(10.20);
Copy the code

4.10 Data type Conversion

Convert other data types to number types -> isNaN, number, pareInt, parseFloat -> when adding, subtracting, multiplying, and dividing data

/ false/true - > 1 - > 0 / / '- > 0' 12 '- >' 12 px '12 - > NaN / 12 / /' guy '- > NaN / / null - > 0 / / undefined - > NaN {} / ^ $/ function () ->NaN [] [12]->'12'->12 ['12,13']->'12,23'->NaN // => Reference data type to a Number // An array is converted to a string through the toString method, then converted to a Number on the call NumberCopy the code

4.10.1 Data operations in JS

  • +, -, *, / addition, subtraction, multiplication and division
  • Except for addition, the other operators are mathematical operations. They also need to convert non-numeric types to number for further operation
1 -'1' -> 0
10*null -> 0
10/undefined -> NaN
10*[10]->100
Copy the code

4.10.2 Particularity of Addition:

  • + is not math when it comes to strings, it’s string concatenation, and it’s math when it doesn’t come to strings
1 +'1' -> '11'
null+'1'- > 'null1'Copy the code
  • String concatenation: Convert other values to strings and concatenate (toString)
  • ToString ==='[Object Object] [Object Object] [Object Object]

4.10.3 Convert other data types to Booleans

  • Boolean,! And!!!!!
  • In the condition judgment, also converted to Boolean type, and then verify the condition is true or false
  • Only 0, NaN, empty string, null, and undefined are converted to false, and the rest are converted to true
[] - >true1 - >true

if(box){// => first fetch the value of the box variable and convert it to a Boolean type, iftrueCondition true, otherwise not true}if(3 +'3px'){// The condition holds: 3 +'3px' = '33px' 
}
if(3 -'3px'){// Condition not true: 3-'3px' = NaN
}
Copy the code

4.10.4 When using == for comparison

When using == for comparison, if the left and right sides of the data are different, the browser defaults to the same type and then compares (‘===’ does not work this way).

[] == [] ->false
var a ={}
var b = a;
a==b -> true
Copy the code

4.10.5 Objects and Numbers: Convert objects to numbers

[] = = 0 >true
({})=== NaN -> falseNaN is not equal to itself and not equal to any other valueCopy the code

4.10.6 Objects and Strings: Converts both sides to numeric comparisons

[] = = =' ' -> true
Copy the code

4.10.7 Objects and Bools: Convert both sides to numbers

[] = =true- > 0 = = 1 - >false[] = =false- > 0 = = 0 - >true! [] = =false- >! [] -> turn the array into a Boolean when taking inverse =false
false=false -> true
Copy the code

String and number: String converts to number String and Boolean: both converts to number Boolean and number: Converts to number

Rule: When two equal signs are compared, the left and right numeric values are of different types. The browser will convert both types to numbers and then compare them. Null ==undefined -> true NULL ===undefined -> false Null ==0 -> false Null and undefined are not equal to any other value

5 common operation statements in JS

5.1 If, else If, else

Judgment action statement

if(conditions1) {//=> Condition 1 is correct
}else if(conditions2) {//=> If condition 2 is true, perform the operation}... else{// => None of the preceding conditions are valid
}
Copy the code

If several conditions are true, only the first condition is executed, and the following conditions are ignored:

A = = B, A! = A>B, A<Bif(A){} // Convert A to A Boolean

/ / n

if(A>B&&A<10) {}// Only two small conditions are true, the whole condition is true

if(A>B||A<10) {}// If one of the small conditions is true, the whole condition is true
Copy the code

BAT interview questions

var num = parseFloat('width: 12.5 px.);
if(num==12.5) {// =>NaN
	alert(12.5);
}else if(num==NaN) {// NaN! =NaN
	alert(NaN);
}else if(typeof num=='number') {// 
	alert(0)}else{
	alert("Nothing.")}Copy the code

5.2 Ternary operators

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

If (conditional){}else: The ternary operator is the simple if.. else.. Another way of writing it

var num = 10;
if(num>5&&num<10){
	num++;/ / accumulation 1
}else{
	num--;
}
// Change to the ternary operator, if the condition is true or not true one of the cases does not require any processing
Void 0 = null; void 0 = undefined; void 0 = void 0
num>5&&num<10? num++:num--;Copy the code
var num = 10;
if(num>5 && num<10){
	num++;
  break;/continue; /return;
}
// => Change to the ternary operator
// We can't use ternary operators to replace if and else because we can't use ternary operators like break, continue, return
num>5 && num<10?
(num++,return) :null;
Copy the code

5.3 swith case

Swith case applies to different operations on a variable with different values in if and else

var num =10;
switch(num){
	//switch contains a value in parentheses (normally we write variables; Use the stored value of a variable, sometimes as a calculation.)
  case 1:
    // the value behind the switch is the same as the value behind the case. break;// Break the case
  case 10:... break;default:
    // The value after switch is not equal to the value corresponding to each case, execute the final default, similar to false. }Copy the code

Case analysis

var num = 5;
switch(num%2) {//=> compare the result of the operation with the case
	case 0:
  num++;
  break;  // No break, no matter if the following condition is true, the execution continues until a break is encountered
    			/ / without break, can realize | | such operations
  case: 2- 1: // count (2-1); // Count (2-1)
  num--;
  // The last item can be broken without a break
  break;
}
num%2: Lets num store the value divided by2To the remainder (0or1)
Copy the code

The more practical “===” in swich case

  • =: assigns, the left side of the equals sign is the variable, the right side is the value
  • ==: compares. If the types on the left and right sides are different, the browser defaults to the same ones and then compares them. ‘6’==6 => 6==6 =>true
  • ===: absolute equality, requiring not only the same value, but also the exact same type

5.4 Loop Operation Statements

To cycle, to do something over and over again

for(Set the start value of the loop; Set conditions for loop execution; Step size summation){// Circulatory body: Anything you do over and over again circulates your weight
}
Copy the code
  • Setting the initial value
  • Validation criteria
  • If condition is true, execute cycle body: if not, cycle lodging
  • Step length accumulation
for(; i<5;;) { consloe.log(i);// Without step size summation, our I is always 0, and the loop condition is always "infinite loop";
  // There can be no dead loop in the project, once it occurs, nothing below the loop can be done
}
Copy the code

5.4.1 the continue

End the loop, continue the next round: the code following the loop weight continue does not execute, it simply executes the step size and proceeds to the next round

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

5.4.2 break

End the whole loop: once the weight of the loop encounters a break, the code behind the first is not executed, and the step size accumulation is not executed, the loop is ended

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

BAT interview questions

for(var i=1; i<10; i+=2) {if(i<5){
  	i++;
    continue;
  }else{
  	i+=3;
    break;
  }
  console.log(i)
}
console.log(i) / / = > 10
Copy the code

5.4.3 the for the in

Used to loop over an object’s key-value pairs

  • var key; var attr(attribute);
  • How many key-value pairs are in the object, how many times does our for in loop traverse (how many times)
  • The first loop key traversal stores the attribute names of the current loop’s group of keys
  • Key stores values in string format (regardless of whether the attribute name is numeric or not)
  • In the for loop in the traversal, most browsers are ordered by the key/value pair in the first object (the digital attributes at the top, and arranged the android Numbers from small to large), the second before the non-numeric attribute name in accordance with the written order, cycle time according to rearrange the step by step a traversal (decimal count letters don’t do Numbers)
var obj = {name:wjw,age:8.0:'wjh'.3:'ylp'.1:'cx'}
for(var key in obj){
    console.log('ok')
    // The key attribute name is string
    console.log(obj.key)
  	->undefined <=> obj['key']
    console.log(obj[key]);
  	//-> For each loop, the value stored in key (the name of the property currently traversed) is put in parentheses, and the corresponding property value of obj is obtained
}
for(var key in obj){
    if(obj.hasOwnProperty(key)){
        
    }
 
}
Copy the code

6 JS DOM get node

The DOCUMENT Object Model provides properties and methods that allow us to manipulate DOM elements

6.1 Node Introduction

A node node. By default, everything in an HTML page is a node (including tags, annotations, text, and so on)

  • Element node :HTML tag
  • Text node: Text content (most browsers treat Spaces and newlines as text nodes)
  • Annotation nodes
  • Document document node

Element nodes

  • nodeType:1
    • Property contains the name of a node
  • NodeName: Uppercase tag name (in the weird mode of some browsers, we write the tag name in lower case, it gets lower case…)
    • For element nodes, nodeValue is not available because it does not contain text directly. Of course, you can also write in the sample and see what happens.
    • For text nodes, nodeValue= text value
    • For attribute nodes, nodeValue= attribute value
  • nodeValue:null
    • For element nodes, nodeType=1
    • For text nodes, nodeType=3
    • For attribute nodes, nodeType=2
    • For annotated elements, nodeType=8
    • For document elements, nodeType=9

[curEle]. TagName: gets the tagName of the current element (usually in uppercase)

Text node

NodeType :3 nodeName:#text nodeValue: text content

Comment node

NodeType :8 nodeName:#comment nodeValue: comment content

A document node

nodeType:9

nodeName:#document

nodeValue:null

<-- div#box>(ul > li $} {0 * 3) + div content ${} * 3 - ><div id="box">
        <ul>
            <li>01</li>
            <li>02</li>
            <li>03</li>
        </ul>
        <div>The content of 1</div>
        <div>Content of the 2</div>
        <div>The content of 3</div>
 </div>
Copy the code

6.2 Obtaining DOM Elements

6.2.1 Document.getelementById an element

  • The context for this method is document only
  • The id of an element in an HTML page is theoretically not repeatable. If the id of an element in the page is duplicated, we get the element object corresponding to the first ID
  • In browsers with earlier versions of IE7, the name value of a form element is used as an ID. (Try not to have the name of a form be the same as the ID of other elements in your project.)
  • If we put js underneath the structure, we can get the element directly with the ID value (without getElementById), and this method will get all elements in the page whose ID is (element object, or collection) => not recommended
<div id="box1"></div><div id="box2"></div><div id="box1"></div>
<script>
   console.log(box1)    // -> [div#box1, div#box1, box1: div#box1]
</script>
Copy the code
<input id="myInput" type="text" size="20"/><br />
<script>
  var x=document.getElementsByName("myInput");
</script>
Copy the code

6.2.2 document. GetElementClassName element collection

  • Context can be specified by itself
  • The result is a collection of elements (class array collection)
  • The result of getting is a set, even if there’s only one item in the set, and we want to operate on that item, we need to get it out of the set and then operate on it
  • While in real projects we often get elements by style class names, the getElementClassName method is not compatible with IE6-8
<input name="myInput" type="text" size="20"/><br />
<script>
  var x=document.getElementsByName("input");
</script>

var bodyBox = document.getElementsByTagName('body');
bodyBox[0].getElementsByTagName('div');
Copy the code

6.2.3 document. GetElementsTagName element collection

<input name="myInput" type="text" size="20"/><br />
<script>
  var x=document.getElementsByName("input");
</script>
Copy the code

6.2.4 document. The getElementsByName node collection

Gets a set of elements (class array: node collection NodeList) from the element’s NAME attribute value, whose context can only be Document

  • Internet Explorer can only recognize the name attribute value of form elements, so this method is generally used to manipulate form elements
  • Get HTML gets the body element object
<input name="myInput" type="text" size="20"/><br />
<script>
 var x=document.getElementsByName("myInput");
</script>
Copy the code

6.2.5 domcument. DomcumentElement get the entire HTML objects

 document.documentElement.clientWidth||document.body.clientWidth
 // Get the width of the current browser viewable area (the width of one screen of the current page)
 // =>clientHieght obtains the height

Copy the code

6.2.6 domcument. Body Obtains the body object

6.2.7 domcument. Head Obtains the entire HEAD object

6.2.8 [Context]querySelector An element object / [context]querySelectorAll Retrieves the set of elements

  • Ie6-8 is not compatible, and there is no particularly good way to handle its compatibility, so these two methods are generally used for mobile development

QuerySelector gets an element object querySelectorAll gets a collection of elements as long as CSS supports selectors, most of which do

document.querySelector('#box1');
document.querySelectorAll('.box1');
document.querySelectorAll('div');
document.querySelectorAll('body>div');
document.querySelectorAll('#box1 li');
Copy the code

6.3 Node Relationship Attributes

Nodes are used to describe the relationship between each department in the page. As long as I can get a page in the page, I can get all nodes in the page through related attributes and methods

6.3.1 childNodes

Gets all the children of the current element (set of nodes: class array) note: Not only the children of the element, but also the text, comments, and so on: the child node description is only looked up in the child generation

6.3.2 children

Fetching all element child nodes (sets of elements) in IE6-8 results differently than in standard browsers (ie6-8 uses comment points as element nodes)

6.3.3 pareNode

Gets the parent node of the current element (element object)

6.3.4 previousibing

Gets the previous sibling of each node of the current node (not necessarily an element node but also text or comment)

6.3.5 nextibling

Gets the next sibling of the current node

6.3.6 previousElementbling

Gets the last sibling of the current node

6.3.7 nextElementsIbling

Node IE6-8 is not compatible with the next sibling of the current node

6.3.8 firstChild

The first of all child nodes of the current element (not necessarily the element node, but text and comments)

6.3.9 lastChild

A fistElementChild lastElementChild(ie6-8 compatible)

6.4 Creating and adding DOM elements

In real projects, we occasionally create HTML tags dynamically in JS and then add them to the page

6.4.1 the document. The createElement method

Dynamically create an HTML tag in JS

6.4.2 the appendChild

Container. AppendChild adds the currently created new element to the end of the container

6.4.3 inserBefore

InserBefore Adds the newly created element before the old element in the current container

/ / create
var oDiv = document.createElement('div');
oDiv.id='div1';
oDiv.className = 'box';

// Add to the page
document.body.appendChild(oDiv);
document.body.inserBefore(oDiv,box2);
Copy the code
var link = document.createElement('a');
link.href = 'http://www.baidu.com?name=1&age=2#haha'

consloe.dir(link);
// hash: store hash value '#haha'
// hostname: domain name 'www.baidu.com'
// pathName: path '/stu/'
// protocol: protocol 'HTTP :'
// search: question mark pass parameter value '? nname=1&age=2'
Copy the code

In real projects, there are many things that need to be done by dynamically creating elements. One of the requirements is to parse each part of a URL (including the parameter value of the question mark).

  • Pure string splitting interception
  • Write powerful re’s to capture the desired results
  • Get the contents of each part individually by dynamically creating an A tag using some of the built-in attributes of the A tag
function queryURLParameter(url){ var link = document.createElement('a'); link.href=url; var search = link.search, obj = {}' if(search.length===0) return; search = search.substr(1).split(/&|=/g); for(var i=0; i<search.length; i+=2){ var key = search[i], value = search[i+1]; obj[key]=value; } link = null; return obj; }Copy the code

6.5 Modifying Deleted cloned DOM elements

6.5.1 removeChild

  • Containers. RemoveChild (elements)
  • Remove each element from the current container

Tactical fix packs for 6.5.2 replaceChild

  • Container. RemoveChild (new element, old element)
  • Clone an identical copy of the original element. False: clone only the current element. True: clone deeply, clone the current element and all its descendants

6.5.3 set/get/remove the Attribute

To set/get/remove attributes for the current element (usually its custom attributes are operated on), box.setAttribute('myIndex'.0)
box.getAttribute('myIndex')
box.removeAttribute('myIndex')
Copy the code

Use xxx.index=0 and xxx.setAttribute(‘index’,0) to set the difference between custom attributes

SetAttribute: Treat the element as a special element object. The set custom attribute is mapped to the DOM element in the page structure

JS element object, we can understand it as two roles:

  • A normal object independent of the HTML structure of a page
  • An element object that maps to the HTML structure of the page

Most of the built-in attributes in the element object map to the page tag: XXX. Style. BackgroundColor = ‘XXX’ at this point not only in the js object corresponding to the attribute value has changed, and will be mapped to the page on the HTML tags (tag has a style inline styles, ClassName = ‘XXX’ not only does the attribute value in the js object change, but the tag in the page adds the class style class (as you can see).

Add a custom attribute to the js object that has nothing to do with the HTML in the page (structurally invisible)

Xxx. setAttribute: Custom attributes set in this way are similar to the built-in attributes mentioned earlier, which are mapped to HTML structures (custom attributes can be displayed on the structure).

6.6 the interview questions

Get all ids in the current page called box1

var allList = document.getElementsByTagName(*);
var result = []
for(var i=0; i<allList.length; i++){var item = allList[i];
  item.id === 'box1'? result.push(item) }console.log(result)
Copy the code

Gets the last sibling of the current element (compatible with all browsers) curEle:current Element

NodeType ===1; nodeType== 1;
// If the node is not based on the current node, find his previous sibling node.. Until the node found is an element node
// If the parent node is not found, the parent node is not found

function prev(curEle){
	var p = curEle.previousSibling; Property returns the previous node of the specified node in the same tree hierarchy.
  while(p&&p.nodeType! = =1) {//p:p! =null
    p = p.previousSibling;
  }
	return p;
}

/ / extension
// next: gets the next sibling element node
// prevAll: Gets all elder element nodes
// nextAll: get all the brother element nodes
// Siblings: gets all siblings
// index: gets the ranking index of the siblings of the current element
Copy the code

Common methods of Math

7.1 Mathematical Functions

But it is of object data type

  • ‘object’
  • The Math object gives us a number of common ways to manipulate numbers
  • Console. dir(Math) // View all methods

7.1.1 abs

Math.abs takes the absolute value

7.1.2 cell / floor

Cell: integer up. Floor: integer down

7.1.3 round

Round: round

7.1.4 random

Random: gets a random decimal between [0,1]

7.1.5 max/minx

Max gets the maximum value of a set of values minx gets the minimum value of a set of values

7.1.6 PI

Math.pi retrieves PI

7.1.7 pow / sqrt

Pow takes what power of a value SQRT takes the square root of a value

8 Character string and common methods

Strings are wrapped in single (double) quotes in JS

var str = 'welcome to credan! '
Copy the code

A string consists of zero to multiple strings

First character index 0 second character index 1… The length property stores the number of characters in the current string (the length of the string).

Indexed by numbers, starting from zero

STR [0] -> ‘w’ strlength-> 46 STR [str.length-1] -> ‘! ‘The last character STR [100] -> undefined gets undefined if the specified index does not exist

In real projects, where we often manipulate strings, we need to learn some common character bed manipulation methods

console.dir(String.prototype)

charAt && charCodeAt

8.1 Str.charCODEAT (index):

On the basis of charAt, change the acquired character into Unicode code value (corresponding to ASCll code table)

  • 48-57 0-9
  • 65-90 A-Z
  • 97-122 a-z
  • .

String. FromCharCode (decimal Unicode value) converts the value to the original character according to the information in the ASCLL code table, which corresponds to charCodeAt

8.2 substr && substring && slice

  • Three ways to implement string interception
  • Str.substr (n.m) : truncates m characters starting from index n
  • Str.substring (n,m): Truncate the part found from index n to index m (inclusive)
  • Str.slice (n,m): and substring syntax meaning, the difference is that slice can be indexed with a negative number

When the index is negative, the browser handles it by adding the total length of the string to the negative index and then treating it as a positive number

Details:

  • If only n(str.substr(n)/str.substring(n)) is passed, it is equivalent to truncating index n all the way to the end of the string
  • If the index passed exceeds the maximum limit, the portion that can be intercepted can be intercepted
  • If none of the arguments are passed: equivalent to intercepting all certificate strings (clone strings)

indexOf && lastIndexOf

  • Str.indexof gets the indexOf the first occurrence of the current character in the string
  • Str.lastindexof gets the index of the last occurrence

If the current character does not appear in the string, the result is -1: we use this rule to verify that the current string contains a character

if(str.indexOf('? ')===-1){// =>if(str.indexOf('? ')>=-1){// =>Copy the code

8.3 the split

Str.split splits a string into an item in an array, corresponding to the join method in the array

8.4 the replace

Replace replaces characters once. Replace can only be replaced once. If several characters need to be replaced, we need to replace them many times if the re does not apply

There are requirements that cannot be implemented by Repalce many times in a timely manner, and regex processing is required. In real projects, replace is usually used with regex

8.5 trim && trimLeft && trimRight

  • Str. trimLeft: Removes the opening space at the beginning of the string
  • Str. trimRight: Removes the opening space at the end of the string
  • Str. trim Removes the space at the beginning of the string

Gets the value of the address bar

function queryURLPrameter(url){
	// => Parameters passed by the URL
  var quesIndex = url.indexOf('? '),
 		  obj = {}
  if(quesIndex === - 1) {// Return null if no question mark is passed in url
  		retrun obj;
  }
  url = url.substr(quesIndex + 1);
  var ary = url.split('&');
  for(var i =0; i<ary.length; i++){var curAry = ary[i].split('=');
    obj[curAry[0]] = curAry[i];
  }
  return obj
}
Copy the code
String.prototype.myQueryURLParameter = function
	myQueryURLParamter(){
	var obj = /([^=?&]+)=([^=?&]+)/g;
  this.replace(reg,function(){
  	var arg = argments;
    obj[arg[1]] = arg[2]})return obj;
}

var str = 'https://www/baidu.com/s?wd=1233213&issp=1';
console.log(str.myQueryURLParameter());
Copy the code

9 Date basics

9.1 Data is the date class

It allows time to be processed

var time = new Date(a);// Obtain the current client native time (the current obtained time is not important for reference)

// The result is an object in date format
// Wed Mar 20 2019 17:37:16 GMT+0800
typeof new DateGetMonth () gets the month time.getDate() gets the day time.getDay() gets the week ()0- 6GetMinutes () gets minutes time.getseconds () gets seconds time.getmilliseconds () gets milliseconds time.getTime() Gets the current date distance'1970-01-01 00:00:00'The milliseconds differentialCopy the code
var time = new Date('2017-10-22'); 
// When passing a time-formatted string in new Date, it is equivalent to transposing the string to a standard time object
// After the transformation is complete, we can call the above methods.
Copy the code

‘2017/10/22 16:15:34’ ‘1508659621314’ ‘// Time format string ‘2017-10-22’ (IE cannot recognize)

Function of the 10 array

10.1 Array infrastructure

  • Typeof [] -> ‘object’
  • An array is also a property name, but the property name is a number, which we call its index: an array is indexed by a number, the index starts at zero, and the length property represents the length of the array


Class array: Similar to an array but not an array

  • The collection of elements obtained by getElementsByTageName is an array of classes
  • The argument collection in a function is also an array of classes


// for loop
for(var i =0; i<ary.length; i++){console.log(ary[i])
}

// for in loop
for(var key in ary){
	// key: attribute name (array attribute name is index)
	console.log(ary[key]);
}

// The for loop can only iterate through private array attributes, while the for in loop can iterate through private array attributes
Copy the code

10.2 Common methods in arrays

There are many methods in an array

console.dir(Array.prototype)
Copy the code
  • The meaning and function of the method
  • Method parameter
  • Method return value
  • Whether the original array is changed by this method

Implement array increase, modify, delete

10.2.1 increase

Push: Appends new content to the end of the array

Parameters: one or more, any data type can be used, want to append to the end of the array, pass directly to the geek in the push method, pass multiple commas to separate the return value: new array length changed

Unshift: Appends new content to the beginning of the array

Parameter: what to append (can be multiple values of any data type) Returned value: The length of the array changed after the addition

Treat the array as a normal object and append the new contents to the end of the array by setting a new property (index) ary[ary.length]= XXX using key-value pair operations on the object

10.2.2 delete

Pop deletes the last item in the array

Parameter: None Returned value: The item to be deleted the original array is changed

Shift: Deletes the first item in the array

Parameter: None Returned value: The contents of the deleted item changed The original array. After shift is used to remove the first item, the index of each subsequent item is moved forward one bit.

Delete :delete ary[index] Deletes the item in the specified index (after the current item is deleted). The indexes of other items in the original array do not change: the length of the current array does not change

Ary.length –: Deletes the last item of the array

Splice: built-in method for adding, modifying, and deleting arrays

Splice (n,m): deletes m columns from index n (m does not write to the end of the deleted column array, and n does not write to the end of the deleted column array) Return value: Deletes the contents (saves in a new array) The original array changed splice(0) Empty the array splice() without deleting any items, Return a new empty array splice(0,1) to delete the first item

Splice is modified

Splice (n,m,x): replaces the deleted content with x

Splice (n,0,x): On the basis of the modification, we do not delete any items. We insert x before the index n, ary. Splice (0,0,x) adds new elements to the end of the array

Array query

Slice array query
  • Slice (n,m) starts at index n and finds at index M (without m)
  • Return value: The part found has been returned in a new array
  • The original array remains the same

Slice (n) finds the trailing slice(0) /slice() array clone starting with index n. Clone a new slice array that is identical to the original array. If the passed index is negative, the browser will parse it as total length + negative index

Concatenate two arrays

Concat: Concatenates multiple arrays together

  • Parameter: The content to concatenate (putting the content after the original array), which can be an array
  • Returns: a new array after concatenation

The original array stays the same

10.3 Querying arrays

Slice: array query parameters: slice(n,m) from index n to find index m (not including m) return value: to find the found part of a new array to return the original array unchanged

Slice (n) find the trailing slice(0)/Slice () array clone, clone a new slice array that is identical to the original array. If the passed index is negative, the browser will parse it as total length + negative indexCopy the code

10.4 Array Concatenation

Concat: Concatenate multiple arrays together Parameter: The content to concatenate (put the content after the original array), can be an array, or some data values return: concatenate new array the original array remains unchanged

let arr = [0.100]
arr.concat([100.200], [200.300].12)
Copy the code

Concat () does not concatenate anything, just clone the original array exactly

10.5 Array to String

10.5.1 toString

Convert an array to a string (the converted string comma separates each item)

Parameter: None Returned value: Converted string Original array unchanged

10.5.2 join

Converts an array to a string with the specified delimiter, corresponding to split in the string

  • Parameter: The specified link symbol
  • Return value: converted string
  • The original array stays the same

Given that each item in the array is a number, if we want to sum the array, how can we do that?

Cycle to achieve

var total = null;
for(var i=0; i<ary.length; i++){ total+=ary[i]; }Copy the code

Using the join

var total = eval(ary.join('+')) // evel: execute string into JS expression
Copy the code

10.6 Sort and arrange each item in an array

10.6.1 reverse

Sort each item in the array upside down

Parameter: None Returned value: Sorted array original array changes

10.6.2 sort

Implement array sorting

Parameter: none or return value of the callback function: sorted array The original array changes without passing arguments: numbers up to 10 can be sorted in ascending order, but more than 10 cannot be processed.

ary.sort(function(a,b){
	return a-b; / / ascending
  return b-a; / / descending
})
Copy the code

10.7 Verify that an array contains an item

10.7.1 indexOf/lastindexOf

Gets the index of the first or last occurrence of positions in the current present array

  • These two methods of arrays are incompatible under IE6-IE8
  • These two methods of string are compatible with all browsers
if(ary.indexOf(12) >- 1) {// The array contains 12
}
Copy the code

10.7.2 principle

Array.prototype.myIndexOf = function myIndexOf(value){
	var result = - 1;
  for(var i =0; i<this.length; i++){if(value===this[i]){
    	result = i;
      break; }}return result;
}
Copy the code

10.8 Method of traversing each item of the number group

The following methods are not compatible with Internet Explorer 6-8

10.8.1 forEach

Iterate over each item in the array

ary.forEach(function(value,index){
	/* The number of items in the array, the number of times the current callback function is executed, the value passed in the first time is the value of the item traversed, index is the index traversed this item */
})
Copy the code

10.8.2 map

Iterate over each item in the array and, on the basis of forEach, modify the value of each item

ary.map(function(value,index){
	/* The number of items in the array, the number of times the current callback function is executed, the value passed in the first time is the value of the item traversed, index is the index traversed this item */
  return xxx;
  // return the result of the current iteration is changed to XXX
})
Copy the code

filter

find

reduce

every

10.9 Array deduplication

Var ary =,2,3,4,5,6,7,1,3,4,5 [1];

Scheme 1 the simplest array deduplication method

Iterate over each item of the number group, compare each item with the item after it, if the same, then delete the same item in the original array

/* * Create a new array, iterate over the incoming array, push the value not in the new array into the new array * */
function uniq(array){
    var temp = []; // A new temporary array
    for(var i = 0; i < array.length; i++){
        if(temp.indexOf(array[i]) == - 1){ temp.push(array[i]); }}return temp;
}

var aa = [1.2.2.4.9.6.7.5.2.3.5.6.5];
console.log(uniq(aa));
Copy the code

Scheme two object key – value method for deduplication

/* * The fastest method takes up the most space (space for time) * * This method executes faster than any other method but takes up more memory. Create a new js object and a new array, traverse the incoming array, determine whether the value is the key of the JS object, * if not, add the key to the object and put the new array. [val]-- n[1], n["1"]; [val]-- n[1]; * To solve the above problem, call "indexOf" again. * /
function uniq(array){
    var temp = {}, r = [], len = array.length, val, type;
    for (var i = 0; i < len; i++) {
        val = array[i];
        type = typeof val;
        if(! temp[val]) { temp[val] = [type]; r.push(val); }else if (temp[val].indexOf(type) < 0) { temp[val].push(type); r.push(val); }}return r;
}

var aa = [1.2."2".4.9."a"."a".2.3.5.6.5];
console.log(uniq(aa));
Copy the code

Scheme three is adjacent division after sorting

/* * Sort the incoming array by adding only values that do not duplicate the previous one. * perverts the order of the original array * */
function uniq(array){
    array.sort();
    var temp=[array[0]].for(var i = 1; i < array.length; i++){
        if( array[i] ! == temp[temp.length- 1]){ temp.push(array[i]); }}return temp;
}

var aa = [1.2."2".4.9."a"."a".2.3.5.6.5];
console.log(uniq(aa));
Copy the code

Scheme four array subscript method

If the first occurrence of the i-th item in the current array is not I, then the i-th item is repeated and ignored. Otherwise, store the result array. * * /
function uniq(array){
    var temp = [];
    for(var i = 0; i < array.length; i++) {
        // If the first occurrence of the ith element in the current array is at position I, the array is stored. Otherwise the representation is repeated
        if(array.indexOf(array[i]) == i){
            temp.push(array[i])
        }
    }
    return temp;
}

var aa = [1.2."2".4.9."a"."a".2.3.5.6.5];
console.log(uniq(aa));
Copy the code

Scheme 5 optimizes the traversal number group method

// Get the original rightmost value and put it in a new array
/* * Recommended method * * method implementation code is quite cool, * implementation idea: the most right value is not repeated into a new array. * (Terminates the current loop and enters the next round of judgment of the top loop when a duplicate value is detected) */
function uniq(array){
    var temp = [];
    var index = [];
    var l = array.length;
    for(var i = 0; i < l; i++) {
        for(var j = i + 1; j < l; j++){
            if (array[i] === array[j]){
                i++;
                j = i;
            }
        }
        temp.push(array[i]);
        index.push(i);
    }
    console.log(index);
    return temp;
}

var aa = [1.2.2.3.5.3.6.5];
console.log(uniq(aa));
Copy the code

11 Fundamentals of Functions

  • A function is a piece of program that works together to do something. Also called subroutines, (in OOP) methods
  • Function A method used to implement a function

11.1 Creating a Function

Functoin [function name](){// => [function body]
    // Implement the function of the specific JS code
}
Copy the code

11.2 Executing Functions

The function name ();// The created function is executed, and this function can be executed many timesThe function name ();Copy the code

Each execution is equivalent to the function weight to achieve the function of the JS code repeatedly executed again

In real projects, we typically wrap code that implements a specific function into a function

  • If the current function needs to be executed multiple times in the page, it will need to be rewritten every time it is implemented, wasting time. And encapsulate in a function, want to realize this function many times in the future, we do not need to rewrite the code, just need to re-execute the function, improve the development efficiency
  • Encapsulating a function makes it almost impossible to repeat the same code in a page, reducing code redundancy and increasing code reuse:Low coupling and high cohesion

We call the above features function encapsulation (OOP object-oriented programming ideas, we need to master is class inheritance, encapsulation, polymorphism)

Core principles of functions in 11.3 JS

Functions, as one of the reference data types in JS, also operate according to reference addresses

function sum(){
	var total = 1+1;
  total *= 20;
  console.log(total.toFixed(2));
}
sum();
Copy the code

11.3.1 Creating a Function

  • We first declare a function name in the current function (var sum; function cum; These two names are duplicated.)
  • The browser first creates a new memory space (complete with a hexadecimal address) and stores the function weight code in this memory space as a normal string (creating a function without executing it makes no sense).
  • Assigns the address of the memory space to the previously declared function name

11.3.2 Function Execution

  • Objective: to implement the js code stored before the specific function
  • Function execution, the browser will first open up new for itPrivate scope(Only the js code previously written in the function can be executed)
  • Parameter value
  • Upgrade a variable in a private role
  • Take the js code strings that were stored at the previous time and put them into the free scope, and execute them from top to bottom as JS expressions
  • The problem of whether the private scope is destroyed





11.3.3 closure

Function execution will form a private scope, so that the private variables and the outside world do not affect each other (mutual interference, the outside can not directly obtain the value of the inside variable), we can understand the private scope to protect the private variables, we call this protection mechanism is called closure

11.3.4 stack memory

Scope (global/private scope): Provides an environment for JS code to execute

11.3.5 heap memory

All reference data types that need to be stored are in heap memory (a repository for information)

  • The object stores the key-value queue
  • The function stores the code as a string

11.4 Parameters and arguments in functions

  • Parameter: equivalent to the entry provided when the washing machine is generated, the user needs to execute the function to pass in the required value, parameter is a variable, used to interface with those values
  • Argument: The specific reference passed to the parameter when executed by the user
// Find the sum of two random numbers

function sum(num1,num2){ //num1/num2
		var total = num1 + num2;
    total*=10;
    total=total.toFixed(2);
		console.log(total);
}

sum(10.20);//10/20 is the argument num1=10 num2=20
sum(10); // num1=10 num2=undefined This parameter is defined but no argument is passed. The default argument is undefined
Copy the code

11.5 Arguments Set of arguments

We can’t set the number of parameters when we don’t know exactly how many values the user wants to pass (as many as you like) : use the built-in argument collection: arguments

  • Argument is only for functions
  • Arguments are inherently pure when a function is executed, whether arguments are passed or not. Arguments are not passed ARG is an empty set that contains all arguments passed
  • All argument information is always stored in the ARG, regardless of whether parameters are set
function sum(){
	console.log(arguments)
}
sum(10.20.'wjh', {name:'wjw'});
Copy the code

  • Arguments is an array of classes
    • Index with a number (attribute name), starting at 0
    • Arguments [0] first argument information
    • Arguments [2] third argument information
    • Arguments [n] n+1 argument information
  • Has a length property that stores the length of the current number of arguments passed.
    • arguments.length
    • arguments[‘length’]
    • Arguments.calle stores the current function itself
    • Arguments.calle. caller stores where the current function is executed (host function), in the global scope, and the result is null
function sum(){
	console.log(arguments.callee.caller);//f
}
function fn(){
	sum(10.20.'wjh', {name:'wjw'});
}
fn();
Copy the code

// Arguments.call or arguments.call. Caller is rarely used in real projects because strict JS mode does not allow us to use these two attributes directly. However, most existing projects are based on strict mode

// Sum any number

function sum(){
	var total = null;
  for(var i =0; i<arguments.length; i++){var cur = Number(arguments[i]);
    !isNaN(cur)? total += cur :null
  }
  consloe.log(total);
  return total;
  // return is followed by a value: many TOTAL variables are returned, but TOTAL is stored as a value
  // return 60;
}
sum(10.20.20);
sum();
sum(10.20.30.'wjw')
// console.log(total); 
//=>Uncaught ReferenceError: Total is not defined The closure protection mechanism causes the scope to protect the private variables inside
Copy the code

Return value in 11.6 JS return

The return value is an exit provided by the function: if we want to use information that is private to the function, we need to return that information for external use

Sum: represents the function itself. Sum () allows the function to execute first. Sum () represents what is returned by the current function

function sum(){
		var total = 0;
    renturn
}
console.log(sum());
// If there is no return or nothing after return, undefined is returned by default
Copy the code
function sum(){
		var total = 0;
    renturn;
    console.log(sum());
  	// When the function weight encounters a return, the code after the return is not executed
}
Copy the code

Anonymous functions in 11.7 JS

A function without a name

  • Functional expression
  • Self-executing function
oBox.onclick = function(){// Assign a function of a code cloud name as a value to an event of a variable or an element, etc., function expression}Copy the code
(function(n){// create function and execute function together, and execute immediately: self-executing function // n parameter n=10})(10function() {} (10) --function() {} (10) +function() {} (10)!function() {} (10)Copy the code