The basic concept

A: JS output method

document.getElementById("").innerHTML=; Document.write (); // the page output console.log(); // console prints alert(); // Popup outputCopy the code

Two: there are three kinds of JS introduction

<script SRC ="js address "type="text/javascript" charset=" utF-8" <body> <button οnclick="alert(123)"> </button> <! --onclick: trigger an event, alert: pop up a dialog box --> </body>Copy the code

JS syntax (variable) :

2. Each statement should end with a semicolon. 3. Variables must start with a letter or _ or $Copy the code

Four: JS naming specification:

1, hump method name myName the second word first letter capitalizedCopy the code

Five: JS notes:

// // single-line comment /* */ / multi-line commentCopy the code

JS has seven data types:

2, (String) String type: with double or single quotation marks. There is no difference between them. Example: "String" 'string' 3, (Boolean) Boolean: trun or false 4, (Object) Object type: new Object {} Typeof returns Object Object 5, (Null) type: Null: Type (Undefined) typeof (object) type (Array) type (Array) New Array[] typeof returns object (Function) type: Function () typeof returns object (Function) type: Function () typeof returns object (Function) type: The let symbol = symbol (argument) method returns a value that is unique and can be used as an identifier for the object. Example: (symbol (1) === symbol (1)) prints falseCopy the code
Note: Undefined, Null, Number, Boolean, and String are defined as basic data types because they are accessed by value and can manipulate the actual values stored in variables. A reference type value is an object that is stored in memory, and when you manipulate an object, you are actually manipulating a reference to the object.

Eight: JS operators:

===(type ===(type ===)) < >! = < = > = 3, && (and, both is true, is true) 4, | | (or, two conditions a is true, is true) 5,! No, the other way aroundCopy the code

Nine: JS loop statement

1, for loop 2, while loop 3, do while loop 4, for in loop over numbers and objects 5, for of loop character)Copy the code

11: JS judgment condition statement

If () else if() else statement 2, Switch () case: break default continue statement 3, (condition)? True: false ternary operator 4. The null-value merge operator // returns values other than null and undefinedCopy the code

Numeric types

Numeric type method

Math.floor(num) rounds down 2 math.ceil (num) rounds up 3 Math.round(num) rounds up 4 Num.tofixed (n) rounds down n digits 5 isNaN(num) indicates whether a number is not a number Math.random() returns a random number of 0~1 decimals. Math.max(num) returns a random number of 0~1 decimals. Math.min(num) to compare the size from, and math.pow (num, number) to return the number of powers of a parameterCopy the code

An array of

We know from the above objects that objects can store collections of keys and values, which is good, but we find that some scenario objects are not very suitable, for example, when we want to insert a new property into an existing element, which is where arrays come in handy, which can store ordered collectionsCopy the code

The statement

There are two syntax options for creating an empty Array: let arr = new Array(); let arr = []; Let arr = ["Apple", 23, "Plum"]; alert( arr[0] ); // Apple alert( arr[1] ); // 23 alert( arr[2] ); // Plum let arr = ["Plum", 23, "Apple"]; alert( arr[0] ); // Plum alert( arr[1] ); // 23 alert( arr[2] ); // Apple We can see from the above code that array elements start at 0 and depend on location, unlike objects, attribute locationCopy the code

Common array methods

  1. Arr.push () description: Adds elements from the end of an arrayCopy the code
  2. Arr.pop () description: Removes an element from the end of an arrayCopy the code
  3. Arr.unshift () adds elements from the head of an arrayCopy the code
  4. Arr.shift () Description: Removes an element from the head of an arrayCopy the code
  5. arr.concat(... Description: Returns an array: copies the current array and adds items, if an array, takes elementsCopy the code
let arr2 = [5, 6]; alert( arr.concat([3, 4]) ); // 1,2,3,4 alert(arr. Concat (arr2)); / / 1,2,5,6Copy the code
  1. Arr.indexof (item, from) Description: Search item from index, return index if found, otherwise return -1.Copy the code
  2. Arr. Find (item, index, array) Arr. Find (item, index, array) Description: Item is an element, index is the search condition, array is the search array, find index, if true, then return itemCopy the code
  3. Arr.findindex () returns the index of an element, just like findCopy the code
  4. Let results = arr.filter() : similar to find, if find element item, add that element to Results, return empty array;Copy the code
  5. Sort (a, b); sort(a, b); sort(a, b); sort(a, b); sort(a, b)Copy the code
  6. Arr.reverse () description: Returns an array that reverses an ARR elementCopy the code
  7. Arr. Split (',') description: Can use a comma as a separator, split into arraysCopy the code
let arr = names.split(', '); for (let name of arr) { alert( `A message to ${name}.` ); // A message to Bilbo (and other names)}Copy the code
  1. Arr.filter () description: The find method searches for the first (single) element that causes the function to return true.Copy the code
  2. Arr.slice () returns a new array that copies all items from index start to end (excluding end) into a new arrayCopy the code
alert( arr.slice(1, 3) ); // e,s (copy elements from position 1 to position 3) alert(arr.slice(-2)); // s,t (copy elements from position -2 to the end)Copy the code
  1. Arr.splice () : Returns the deleted array, taking three arguments: the number from which to delete, the number of deletions, and the content addedCopy the code
    arr.splice(0, 3, "Let's", "dance");
    alert( arr ) // now ["Let's", "dance", "right", "now"]
Copy the code

string

String methods

Str.touppercase () converts toUpperCase; str.tolowercase () converts toLowerCase; str.tolowercase () converts toLowerCase; 4, str.lastIndexof () 5, str.includes() true, false 6, str.startswith () true, 8, str.splice(start, end, item1... ItemN) returns the deleted string from the start to end part, and adds item1... ItemN 9, str.slice(start, end) returns string from start to end(excluding end) 10, str.subString (start, end) returns string from start to end(excluding end), Run str.substr(start, length) to return the string from start and obtain the length part 12. Str.trim () Deletes the Spaces before and after the string 13. Str.repeat (n) repeats the string n timesCopy the code

function

A function is a program in which the code inside a function can be called repeatedly, without having to write the code repeatedlyCopy the code

Function declaration

function hello() { alert( 'Hello everyone! '); } Hello is the name of the functionCopy the code

Anonymous functions

function () { alert( 'Hello everyone! '); } No function name is an anonymous functionCopy the code

Four ways to call anonymous functions

Var a=function(){console.log("Hello World! ); } a(); Function (){console.log("Hello World! ); }) (); Function (){console.log("Hello World! ); } ()); / / fourth method [function () {the console. The log (" Hello World! ");} ()];Copy the code

Functional expression

let hello = function() { alert( "Hello" ); }; This is where the function is created and assigns its value to Hello.Copy the code

The constructor

1. Their names begin with a capital letter. 2. They can only be executed by the "new" operator. For example: function User(name) {this.name = name; this.isAdmin = false; } let user = new User("Jack"); alert(user.name); // Jack alert(user.isAdmin); // falseCopy the code

Nested function

Create another function inside one function, Function sayHiBye(firstName, Function getFullName() {return firstName + "" + lastName; } alert( "Hello, " + getFullName() ); alert( "Bye, " + getFullName() ); }Copy the code

Passing in multiple parameters

Function sum(a, b) {return a + b; function sum(a, b) {return a + b; } alert( sum(1, 2, 3, 4, 5) ); //3 As can be seen from the above code, only two arguments are called. We can use Rest arguments... SumAll () function sumAll(... Args) {// let sum = 0; for (let arg of args) sum += arg; return sum; } alert( sumAll(1) ); // 1 alert( sumAll(1, 2) ); // 3 alert( sumAll(1, 2, 3) ); Function sumAll(a, b...) function sumAll(a, b... Args) {// let sum = 0; for (let arg of args) sum += arg; return sum; } alert( sumAll(1) ); // 1 alert( sumAll(1, 2) ); // 3 alert( sumAll(1, 2, 3, 4, 5) ); / / 15Copy the code

closure

"Closures are functions that can read variables inside other functions. In javascript, for example, local variables can only be read by child functions inside a function, so closures can be understood as "functions defined inside a function." In essence, closures are Bridges that connect the inside of a function to the outside of a function."Copy the code

scope

We know from closures that normally only external variables can be read from the inside, not internal variables (there are methods). This is the scope of functions {// Do some work with local variables that are not visible outside the code block. Alert (message) is visible only within this code block; // Hello } alert(message); // Error: message is not definedCopy the code

How do I read variables inside a function from outside?

This is a common situation, and I recommend three approaches (and more).Copy the code

First access via return:

function bar(value) { var testValue = 'inner'; return testValue + value; } console.log(bar('fun')); // "innerfun" return returns only the variable (testValue + value), you also need to call the function to get (bar('fun')); Function bar(value) {var testValue = 'inner'; } console.log(bar()); Function bar(value) {var testValue = 'inner'; function bar(value) {var testValue = 'inner'; return testValue; } console.log(testValue); //testValue is not defined. If testValue is called directly, an error is reported because internal variables cannot be readCopy the code

Second, access internal variables via closures:

function bar(value) {
  var testValue = 'inner';
  var rusult = testValue + value;
  function innser() {
     return rusult;
  };
  return innser();
}
console.log(bar('fun'));		// "innerfun"
Copy the code

Third execute the function immediately:

Use it to separate the global scope into a single function scope. <script type="text/javascript"> (function() { var testValue = 123; var testFunc = function () { console.log('just test'); }; }) (); console.log(window.testValue); // undefined console.log(window.testFunc); // undefined </script>Copy the code

“The new Function” grammar

This method of creating a function is actually used very rarely, but it is special, so I will write it laterCopy the code

grammar

let fun = new Function()
Copy the code

Special point

function getFunc() { let value = "test"; let func = new Function('alert(value)'); return func; } getFunc()(); // error: value is not defined. So that's what's special about new Function, when we use new Function to create a Function, it's not going to point to the current syntax environment, it's going to point to the global environment, so when we call value, which is actually a global variable, you can try adding a global variable value, Isn't it special?Copy the code

conclusion

A function can read a variable from the inside of its scope, but it cannot read a variable from the outside of its scope. Return (' import ', 'export', 'import'); return (' import ', 'import'); 4. New Function refers to the global environment.Copy the code

Object

object

You can think of an Object as a drawer that has a file in it, a file with a person's name on it, and a value inside it like we create an empty Object let user = new Object(); // let user = {}; // "literal" syntax let caomaoHaiZeiTuan = {a object (drawer) chuanzhang: "lufei ", name is the name, : right is the object (value) age: JiNeng: 'Rubber machine gun', jingEr: '1 billion bounty', Chuanyuan: 'Soolon', Name: 'key', : right: value age2: "18", age is the name (key), : right is the object (value) "800 million reward",} simply speaking, the object is more authentication (attribute), before the establishment of straw hat pirate group, we used to call Lufei lufei, when the straw hat pirate group is established, we should all call, a, it is caomaoHaiZeiTuan captain lufei, Age (age)22, skill (jiNeng) is rubber machine gun, bounty (jingEr)1 billion ah ha! An object can contain multiple properties, and values can be read from different propertiesCopy the code

Object reference

let user = { name: "John" }; let lada = user; // Are they two numbers? Let user = {name: 'John'}; let user = {name: 'John'}; let lada = user; lada.name = 'hello'; // Modify alert(user.name) with a" lada" reference; // 'hello', the modification can be seen by referring to "user" remember basic concepts question 6? That's the difference between a reference type and a basic type. What if we wanted to copy a reference to that object or clone a new object completely (without referencing each other)? Look at shallow copies (copying references) and deep copies (completely independent and not affecting each other)Copy the code

Shallow copy

Three ways (and more)

// create a new object, Let obj = {name:'AAA', age:18} let obj1 = {name:obj.name, age:obj.age } obj1.name = 'BBB' // console.log(obj); // AAA // console.log(obj1); Let obj2 = {} for(let key in obj){obj2[key] = obj[key]} obj2.name = 'CCC' // console.log(obj); // AAA // console.log(obj2); // CCC // 3, object.assign () let obj3 = object.assign ({},obj) obj3.name = 'DDD' console.log(obj); // AAA console.log(obj3); // DDDCopy the code

Deep copy

Three ways (and more)

Json.stringify converts an object to a string, and json.parse converts a string to a new object. Functions cannot be converted to JSON, and RegExp objects cannot be deep-copied this way. Parse (json.stringify (obj)) // demo-- const obj1 = {a: 1, b: 2} const obj2 = JSON.parse(JSON.stringify(obj1)); obj1.a = 2; console.log(obj1); // { a:2, b:2 } console.log(obj2); // {a:1, b:2} undefined, function and symbol are invalid for the original object, because these three values will be ignored in the conversion process, so using this method for the object with these three attributes will cause the data loss of the above three attributes. But it's easy and quick to use for data that doesn't have any of these attributes. Lodash is one of the most popular libraries in the world. Loadsh import _ from 'loadsh' var obj= [{lodash.clonedeep ()) {lodash.clonedeep (); 'a': 1 }, { 'b': 2 }]; var deep = _.cloneDeep(obj); console.log(deep[0] === objects[0]); Function deepClone(source) {if (! source) return let target; If (typeof source === 'object') {if (typeof source === 'object') {target = array.isarray (source)? [] : For (let key in source) {if (source.hasownProperty (key)) {if (typeof source[key]! == 'object') {target[key] = source[key]} else {// If internal attributes have complex data types, Target [key] = deepClone(source[key])}}}} else {target = source} return target}Copy the code

The prototype

Archetype, inheritance, implicit archetype, prototype chain

I'm sure many of you have heard these words, but don't quite understand what they meanCopy the code
A prototype is a Prototype property. Every function has a Prototype property
An implicit stereotype is actually a __proto__ property, every object has a __proto__(implicit stereotype) property
Inheritance is when an object’s _proto_ attribute points to an object that the constructor’s Prototype attribute points to
The prototype chain is the chain in which the _proto_ property of the object points to the prototype property of the constructor

Function Outer() {name: "三"} let animal = {eats: true}; let rabbit = { jumps: true }; Prototype Outer._proto_ //ƒ () {[native code]} rabbit.__proto__ = animal; rabbit.eats //eats: true rabbit.prototype = animal; : : uses undefined animal. Eats =true: jumps //undefined animal. Eats =true: uses undefined animal. Prototype = animal; rabbit = animal; prototype = animal; Implicit prototypes can be inherited from the rabbit.prototype //undefinedCopy the code

What are the methods of type identification

Respectively is: 1. Typeof2. Object. The prototype. ToString3. Constructor4. InstanceofCopy the code
  1. typeof

The return value is a string that specifies the type of operand. Typeof normally only returned the following results: the number, Boolean, string, the function, object, undefined

console.log(typeof 'abc');  //string
console.log(typeof 1 );  //number
console.log(typeof true );  //boolean
console.log(typeof undefined );  //undefined
console.log(typeof null );  //object
console.log(typeof {name: 'moon'} );  //object
console.log(typeof function () {} );  //function
console.log(typeof [] );  //object
console.log(typeof new Date() );  //object
console.log(typeof /\d/ );  //object
function Person() {}
console.log(typeof new Person() );  //object
Copy the code

Only primitive types (except null) are recognized, not object types

  1. Object.prototype.toString

It can rigorously identify primitive types and object types

/ / the method first encapsulated into a function the function type (obj) {return Object. The prototype. ToString. Call (obj). Slice (8, 1); } // String intercepts the part of console.log(type('moon')) we need; //String console.log(type(1)); //Number console.log(type(true)); //Boolean console.log(type(undefined)); //Undefined console.log(type(null)); //Null console.log(type({})); //Object console.log(type([])); //Array console.log(type(new Date())); //Date console.log(type(/\d/)); //RegExp console.log(type(function () {})); //Function function Person() { } console.log(type(new Person())); //ObjectCopy the code
  1. constructor

View the constructor of the object

4.instanceof

Determine the relationship between objects and constructors

Var a=new Array(); console.log(a instanceof Array); //true console.log(a instanceof Object); Function test(){}; function test(){}; var a=new test(); console.log(a instanceof test); Console. log(1 instanceof Number); //true // Console. log(1 instanceof Number); //false console.log('moon' instanceof String); //falseCopy the code

this

This is one of the most important, novice to this is very easy to confused, ES5, in fact, as long as you remember a sentence: ** who calls this, this refers to who **, remember this sentence, coupled with my use of the following scenarios, understand is no problem.Copy the code

Scenario 1: The this point in the global environment is the global object

Var name = 'c '; Function a(){var name = 'sleep '; console.log(this.name); // eat console.log("this points to :" + this) //this points to :Window} a(); This. Name should refer to "sleep". Remember what I said at the beginning? ** Whoever calls this, this refers to whoever **. When we call a(), we find that there is no object in front of a(), so we call the global object window.a (). This cannot be in strict mode, otherwise for undefinedCopy the code

Scenario 2: The this of the function inside the object refers to the current object calling the function

Var name = ""; Var a = {name: "sleep ", test: function () {console.log(this.name); Var name = "eat "; var name =" eat "; var name = "eat "; Var a = {name: "sleep ", test: function () {console.log(this.name); }} window.a.test();}} window.a.test();}} window.a.test();Copy the code

Scenario 3: This in an anonymous function points to a global object

Var name = ""; Var a = {name: "sleep ", test: (function () {console.log(this.name); })()} a.test() {if this function is a global variable with no pointer, it refers to the window object.Copy the code

Scenario 4: This in setInterval and setTimeout timers points to a global object

Var name = ""; Var a = {name: "sleep ", func1: function() {setTimeout(function() {console.log(this.name)},100); }}; SetTimeout is an anonymous function. SetInterval's var name = "eat "; Var a = {name: "sleep ", func1: function() {setInterval(function() {console.log(this.name) clearInterval(a)},100); }}; a.func1()Copy the code

Scenario 5: The this in the constructor points to the constructed new object

Function Person(name,age){this.name = name; this.sayName = function(){ console.log(this.name); }} var a = new Person(' sleep '); a.sayName(); The this in the constructor refers to the new object being constructed, which new Person() already callsCopy the code

Scenario 6: This in new Function points to a global object

Function Foo(){var f = new function("alert(this.name)"); var f = new function("alert(this.name)"); f(); //[object Window] } } var foo = new Foo(); foo.bar(); If f() calls this, this refers to the name of the global object. If f() does not have its own name, it refers to the name of the global object.Copy the code

ES6 arrow function

The previous scene is actually ES5, now look at the special ES6 arrow function this, arrow function need to remember this: Arrow functions do not have this binding, so the value must be determined by searching the scope chain. If the arrow function is contained by a non-arrow function, this is bound to the nearest non-arrow function. Otherwise, this is undefinedCopy the code
Apply the code for scenario 4
Var name = ""; Var a = {name: "sleep ", func1: function () {setTimeout(() => {console.log(this.name)},100); }}; Var name = 'eat'; var name = 'eat'; var name = 'eat'; var name = 'eat'; Var a = {name: "sleep ", func1: function () {console.log(this.name)}, func2: function () {console.log(this.name)}, func2: function () { setTimeout( () => { this.func1() },100); }}; A.f unc2 () / / go to bedCopy the code

Three ways to change this

You can also change the direction of this using apply, call, and bindCopy the code
apply
Var name = ""; Var a = {name: "sleep ", test: function(){console.log(this.name); }}; A.test () // sleep a.test. Apply () // eat A.test. Apply (a) // Sleep. I'm sure you've seen how apply changes this, yes, apply(this)Copy the code
call
Var name = ""; Var a = {name: "sleep ", test: function(){console.log(this.name); }}; A.test () // sleep a.test. Call () // eat a.test. Call (a) // sleep a.testCopy the code
bind
Var name = ""; Var a = {name: "sleep ", test: function(){console.log(this.name); }}; Bind () a.test.bind() a.test.bind() a.test.bind() Bind (a)() // Eat. Bind (a)() // Sleep appears again, obviously you need to bind it againCopy the code
Apply, call, and bind
Now that we know how to use apply, call, and bind to change this, what are the differencesCopy the code
Apply is different from call
In fact, apply and Call are basically similar, the only difference is that they pass different parameters. The difference between Apply and call is that the call method accepts a list of arguments, while Apply accepts an array of arguments. Var name = ""; Var a = {name: "sleep ", test: function(a,b){console.log(this.name + a + b); }}; A.t est. Apply (a, [" playing games ", "toilet"]) to sleep / / play games toilet var name = "to eat"; Var a = {name: "sleep ", test: function(a,b){console.log(this.name + a + b); }}; Call (a," play video games "," go to the bathroom ") // Play video games to go to the bathroomCopy the code
Call is different from bind
Var name = "bind "; var name =" bind "; Var a = {name: "sleep ", test: function(a,b){console.log(this.name + a + b); }}; A.test. call(a," play games "," go to the bathroom ") // var name = "eat "; Var a = {name: "sleep ", test: function(a,b){console.log(this.name + a + b); }}; Bind (a," bind "," bind ")() // Bind (a," bind "," bind ")() // Bind (a," bind "," bind"Copy the code
A final note: This is my first article, I just learn more than half a year of front-end rookie, if there is anything wrong can be corrected, we learn and progress from each other, here is just to talk about JS commonly used, there are a lot of not written, LATER I will gradually write ES6, Vue and so on to see if it can form a series, I will write the things I have learned in this half year step by step, to their own knowledge to a preservation. If you think it’s ok, give it a thumbs up! Writing really tired, because every code I have to verify, after all, I am also a rookie, can not mislead others