In the words of my little sister, ** beauty ** is open for business ~~~

Article length is longer, you can choose their own content to view!! This layout is a little messy, you can scan the code to view the original public account

I, a junior in school, started a systematic review in order to sprint for spring recruitment. As for why I reviewed these basic problems, it was natural that I repeatedly hit a wall in the basic content. (Ps: HERE I would like to thank all the beautiful brothers and handsome sisters who helped me in my study, especially the cute ones who encouraged me when I was confused.) I only record my study in a series of articles, or it can be a detailed review outline. As for a large part of the in-depth content of the recommendation we go to see the small red book (front small red book ha **). If it is helpful, I would like to share with you

The content is for reference only you can pay attention to any questions xiaomao discussion ~

Javascript is a must-have technology for everyone on the front end, so you must learn it well

Due to the limited space, this article only Js basic, will continue to update you ~

Context diagram

Javascript first

What is the JavaScript

JavaScript is one of the most popular languages in the world. It is a scripting language that runs on the client side.

* Scripting language: no compilation is required, the JS interpreter (JS engine) interprets and executes line by line during execution

Server-side programming is now also possible based on Node.js technology

The Javascript function

Form dynamic verification (password strength detection) (the original purpose of JS generation), Web effects, Server development (Node.js), Desktop application (Electron),App(Cordova), Control hardware – Internet of Things (Ruff)

HTML | CSS/JavaScript difference contrasts

①HTML/ CSS markup language —- TML determines the structure and content of a web page (decide what to see), similar to the human body CSS determines the appearance of a web page presented to the user (decide not to look good), 2 JavaScript—- scripting language —- programming language to achieve business logic and page control (decision function), equivalent to a variety of human actions

How does the browser execute JS

The browser is divided into two parts: the rendering engine and the JS engine

Rendering engine: used to parse HTML and CSS, commonly known as kernel, such as Blink in Chrome, older versions of WebKit

JS engine: for THE JS interpreter. It is used to read JavaScript code from a web page, process it and run it, such as Chrome V8

The browser itself does not execute JS code, but rather uses a built-in JavaScript engine (interpreter) to execute JS code. The JS engine interprets the code line by line

Each line of source code (translated into machine language) is then executed by a computer, so JavaScript is a scripting language that interprets execution line by line. (This can be explained line by line in scripting language)

Of Javascript

1) ECMAScript — — — — — javascript syntax

ECMAScript defines the javascript syntax and basic core knowledge. ECMAScript is an industry standard for JAVASCRIPT syntax followed by all browser vendors (Netscape/Microsoft).

②DOM————- page document object

Document Object Model (DOM) is a standard programming interface recommended by W3C to deal with extensible Markup language.

The DOM provides interfaces to manipulate various elements on the page (size, position, color, and so on).

③BOM————- Browser object model

BOM (Browser Object Model) refers to the Browser Object Model, which provides a content-independent Object structure that can interact with the Browser window. The BOM allows you to operate browser Windows, such as pop-up boxes, control browser hops, and obtain resolution

Javascript to write

Note: occasionally encountered this question, I asked in an interview, but generally asked to write in different places of the difference ~

(1) inline

< p style =" max-width: 100%; clear: both; min-height: 1em;

(2) embedded

The script tag in the body below the title

<! -- 2. Inline --> <! -- <script> alert("lllllllll"); </script> -->Copy the code

(3) outside the chain

<! <script SRC ="myjs.js"></script>Copy the code

Javascript variable

Use of variables

Variable: a block of memory allocated by a program to store data.

(1) statement

// Declare variables

var age; // Declare a variable named age

(2) the assignment

age = 10; // Assign the age variable to 10

(3) initialization

var age = 18; // declare the variable and assign it to 18

Variable syntax extension

① Update variables

var age = 18;

age = 81; // The final result is 81 because 18 is covered

② Declare multiple variables at the same time

var age = 10, name = ‘zs’, sex = 2;

③ Declaration of special circumstances

Variable naming conventions

1. The value consists of letters (A-ZA-z), digits (0-9), underscores (_), and dollar signs ($), for example, usrAge, num01, _name

2. Be case sensitive. var app; And var App; Is two variables

3. Do not start with a number. 18age is incorrect cannot be a keyword, reserved word. For example: var, for, while

4. Variable names must make sense. MMD BBD NL → age

5. Follow the hump nomenclature. The first letter should be lowercase. The first letter of the following words should be capitalized. myFirstName

Exercise – Swap variables

<script> var temp; Var apple1=' green apple '; Var apple2=' red apple '; temp=apple1; apple1=apple2; apple2=temp; console.log(apple1); console.log(apple2); </script>Copy the code

Javascript data types

Why distinguish between data types

In a computer, different data require different storage space. In order to facilitate the data into different memory size data, make full use of storage space.

The JS data type is determined by the value following the equal sign

Simple data types

The operating system divides the system into two large blocks: the heap and the stack

Simple data types are stored on the stack, and directly open space for values

(1) the Number

The integer + decimal default value is 0

The maximum Numbe. RMAX_VALUE

The minimum Number. MIN_VALUE

Three special values:

Infinity, which stands for Infinity, greater than any number

-Infinity, which stands for infinitesimal, less than any number

NaN, Not a number, represents a non-numeric value

IsNaN (); Return value (false if number, true if not)

(2) Boolean

True

False

Note: When evaluating values true=1 false=0

(3) String

As long as the string is concatenated with other data types = string

(4) Undefined

A declared variable that has not been assigned a value will have a default value of undefined

Note: Output value problem

* unfined + = NaN

* UNpay + string = String stitching

*undefined(declare unassigned)+ Boolean true=NaN

5. Null

Null, returns an empty object

* NULL + string = string concatenation

* NULL + number = the number

Complex data types

Complex data types are stored in the heap, and the heap is looked up by the address in the stack

(1) the Object

Get variable types

1. Determine the console color

2. Typeof checks the data typeof variables

console.log(typeof num); //number

Typeof + space + variable = direct detection

Typeof null=object

Prompt (‘ enter: ‘); The value that prompt pulls out is of character type

Javascript data type conversion

Convert to string

Convert to numbers

ParseInt —— converts characters to integer data with units such as 120pxAutomatically remove unitsRound not a number: rem120px– NaN

Convert to Boolean

Boolean (variable)

Values representing null and negative are converted to false, such as ”, 0, NaN, null, undefined

All other values are converted to true

Exercise – Boolean judgment

console.log(Boolean('')); // false console.log(Boolean(0)); // false console.log(Boolean(NaN)); // false console.log(Boolean(null)); // false console.log(Boolean(undefined)); // false console.log(Boolean(' small white ')); // true console.log(Boolean(12)); // trueCopy the code

Javascript operator

Arithmetic operator

+ | | | * /

Floating-point precision problem: Floating-point values have a maximum accuracy of 17 decimal places, but are far less accurate in arithmetic than integers

Var result = 0.1 + 0.2; // The result is not 0.3, but 0.30000000000000004

Self-addition and subtraction operators

①++num/–num–

Equivalent to num = num + 1

Num=10; (num=num+1=11),(++num)=11

②num++/num—–

The effect is the same when used alone

Num++=++num====num=num+1

Post: return the original value first, then add

Age=10; (age++)=10 ,age=11;

Practice – add and subtract

var a = 10; ++a; //a=11 var b = ++a + 2; //12+2 console.log(b); var c = 10; c++; //c=c+1=11 var d = c++ + 2; //(c++)+2=11+2=12 console.log(d); var e = 10; //e++---e=11 var f = e++ + ++e; //(10)+(11+1)=22 console.log(f);Copy the code

Comparison operator

Logical operator

The assignment operator

Operator priority

Bracketing -> the unary operator (! Highest)-> arithmetic operator (multiply and divide before addition and subtraction)-> relational operator -> equality operator -> logical operator (and after or)-> assignment operator -> comma

Javascript Flow control

Sequential structure

Branching structure

1.if-else

Exercise – Judge leap years
Var year=prompt(" please enter the query year: "); / / can be divided exactly by 4 and can not be divided exactly by 100 is a leap year (such as 2004 is a leap year, 1901 is not a leap year) or can be divided exactly by 400 is a leap year if (4 = = 0 year % && year % 100 | | 400 year % = = 0) {alert (" you can query the year is a leap year!" ); }else{alert(" the year you query is not a leap year, please return to home page if you need to query other information "); }Copy the code

2.if-else-if

Practice – Grades
Var score = prompt(' please enter score :'); if (score >= 90) { alert('A'); } else if (score >= 80) { alert('B'); } else if (score >= 70) { alert('C'); } else if (score >= 60) { alert('D'); } else {alert(' fail ');Copy the code

3.switch-case

Branch query problems

4. Ternary operators

If expression 1 is true, the value of expression 2 is returned; if expression 1 is false, the value of expression 3 is returned

Loop structure

Loop problem: execute a piece of code repeatedly

1.for

2. Nested

Exercise – Print the multiplication table
var str=""; for(var i=1; i<=9; i++){ for(var j=1; j<=i; j++){ str=str+j+"X"+i+"="+i*j+'\t'; } str=str+'\n'; } console.log(str);Copy the code

3.while

4.do-while

Execute the loop body once before judging the condition

5. The key word

​ (1)contuine

Jump out of this loop immediately and continue with the next loop

​ (2)break

Exit the entire loop

Javascript array

Array: An array is a collection of data, each of which is called an element. An array can hold any type of element. (A lot of data can be stored at one time)

Create an array

New

var arr=new Array();

literal

Arrays can hold data of any data type, separated by commas

* Declare an array and assign = Array initialization

var arr=['xiaomao'.2.true.8]
Copy the code

Getting an array element

 var arr=['xiaomao'.2.true.8]
       // Get the element
       console.log(arr[1]);
Copy the code

Array traversal

 var arr=['xiaomao'.2.true.8]
       for(var i=0; i<=arr.length; i++){console.log(arr[i]);
       }
Copy the code

Add an array element

By changing length

By modifying the array index

var arr = [];
        for (var i = 0; i < 10; i++) {
            arr[i] = i + 1;
        }
        console.log(arr);
Copy the code

Exercise – Array
Taking the maximum
Var arr =,6,1,77,52,25,7 [2]; var max=arr[0]; for(var i=0; i<arr.length; i++){ if(arr[i]>max){ max=arr[i]; } } console.log(max);Copy the code
An array of screening
var arr=[2, 0, 6, 1, 77, 0, 52, 0, 25, 7]; var arr1=[]; For (var I =0; i<arr.length; i++){ if(arr[i]>10){ arr1[arr1.length]=arr[i]; } } console.log(arr1);Copy the code
An array of reverse

Var arr = [6]; var arr1=[]; Var I =arr. Length -1; i>-1; i--){ arr1[arr1.length]=arr[i]; } console.log(arr1);Copy the code
Bubble sort

Var arr =,4,3,2,1 [5]; for(var i=0; i<arr.length-1; Var j=0; var j=0; j>arr.length-i-1; J++) {/ / / / number of complete variable exchange -- -- -- -- -- - before and after a compare the if (arr [j] > arr [j + 1]) {var temp = arr [j]; arr[j]=arr[j+1]; arr[j+1]=temp; }}}Copy the code

Javascript function

Function: encapsulates a block of **** code **** that can be called repeatedly. You can reuse a lot of code with this block

If a function is not called, it never executes itself

Function USES

① Function declaration

1. Custom function method

function fn1(){

     / / the function body

   }
Copy the code

2. Anonymous function method

  var fn2=function(){
            / / the function body
        }
Copy the code

② Function call

// Call the function

The function name ();

③ Function encapsulation

Function encapsulation encapsulates one or more functions in the form of functions and provides only a simple function interface

Parameters of a function

parameter

The argument inside the parentheses of a function declaration, which in JavaScript defaults to undefined, is used to accept arguments, similar to variable assignment

The arguments

Arguments passed when a function is called

The number of parameters does not match

Function return value

Function name () =return result after return

Return returns only one value. If multiple values are separated by commas, the last one takes effect.

Returns undefined if the function does not return

Exercise – function use
Var arr1 =,2,99,101,67,77 [5]; function getArrMax(arr){ var max=arr[0]; for(var i=0; i<arr.length; i++){ if(arr[i]>max){ max=arr[i]; } } return max; } //getArrMax(arr1); var result=getArrMax(arr1); console.log(result);Copy the code

Arguments

You can use arguments to get arguments when you are unsure how many arguments to pass. In JavaScript, arguments is actually a built-in object for the current function. All functions come with a built-in arguments object, which stores all arguments passed.

The *arguments presentation form is a pseudo-array *, so it can be iterated over.

Pseudo-array features: it has the length attribute, stores data in the way of index, and does not have the methods of array push. Pop and so on.


The exercise-arguments object maximizes data
 function maxValue() {
            var max = arguments[0];
            for (var i = 0; i < arguments.length; i++) {
                if (max < arguments[i]) {
                    max = arguments[i];
                }
            }
            return max;
        }
        console.log(maxValue(2, 4, 5, 9));
        console.log(maxValue(12, 4, 9));
Copy the code
Knock key: scope, pre-analysis, the object of these sections for the interview pen often test points, because of the space is limited, only a brief introduction. At the same time, little Maurolet’s exercises are representative but not necessarily very practical, if you have a good question to share with me, xio.

When I was learning this, I wrote a small blog that I think is relatively easy to understand. If you want to see it, you can go to Kangkang ~ (portal: blog.csdn.net/qq_43594636…

Because I pure science and engineering, language expression is very clumsy, we forgive ha

Vernacular Chinese is easier to understand

scope

Scope: A collection of accessible variables, objects, and functions

Improve program reliability and reduce naming conflicts

1. Global scope

Applies to the entire script tag, or to a single JS file

2. Local scope

Inside a function, the name only works inside a function

Variable scope

1. Global variables

Variables declared in a global scope can be used anywhere, and can only be destroyed if the browser closes the variable, which takes up a lot of memory. * Internal assignment of only undeclared variables —->> global variables

2. Local variables

Variables declared in a local scope take effect only inside a function. Destroying code blocks immediately after completion saves space

Function parameters —–>> local variables

The scope chain

In cases where an inner function has access to an outer function variable, a chain lookup to determine which data can be queried by the inner function is called a scope chain

* Find the value of a variable nearby


Scope chain exercises
1. Scope judgment
Function f1() {var num = 123; //fn1 local function f2() {console.log(num); } f2(); } var num = 456; / / global f1 ();Copy the code
2. Scope chain finds variables
var a = 1; function fn1() { var a = 2; var b = '22'; fn2(); function fn2() { var a = 3; fn3(); function fn3() { var a = 4; console.log(a); // Find console.log(b) in the number 4 fn3; }}} fn1();Copy the code

Javascript preliminary analytical

JavaScript parsers run JavaScript code in two steps: pre-parsing and code execution

**** pre-resolution: **** In the current scope, the browser defaults to pre-definition of variables and functions with the keywords var and function before executing the JS code. Pre-resolution only occurs on variables and functions defined by var.

* Code execution: * Execute JS statements from top to bottom.

Variable preresolution

Variable declarations are promoted to the front of the current scope; assignment is not promoted

 console.log(num);//undefined ---->>var num; console.log(num); num=10
        var num=10;
Copy the code

Function preparsing

fn1();
       var fn1=function(){
           console.log(22);/ / an error
       }
       Var fn1; fn1(); fn1=function(){console.log(22); }
Copy the code

Practice – pre-parsing
var num = 10; function fn() { console.log(num); //undefined var num = 20; console.log(num); //20 } fn(); Var num; var num; function fn() { var num; console.log(num); //undefined undefined value num=20; console.log(num); } num=10; fn();Copy the code

Scope chain classic interview questions

f1(); console.log(c); //9 console.log(b); //9 console.log(a); Function f1() {var a = b = c = 9; console.log(a); //9 console.log(b); //9 console.log(c); Function f1() {var a=9; b-9; c=9; var a; a=9; b=9; // Direct assignment is equivalent to the global variable c=9; console.log(a); console.log(b); console.log(c); } f1(); console.log(c); console.log(b); console.log(a);Copy the code

Javascript object

In JavaScript, an object is an unordered collection of related properties and methods. Everything is an object, such as strings, numbers, arrays, functions, etc.

Object = Property (trait) + Method (behavior)

Why objects: Clean structure and easy storage

Object creation

Literal mode

   // Create a literal
        var girl = {
            name'xiaomao'.age19.sex'woman'.sayHifunction ({
                alert('Hello~'); }};/ / call
        console.log(girl['name']);
        console.log(girl.name);
        // method call
        gril.sayHi();
Copy the code

The New keyword is created

//new Obect
        var meinv= new Obect();
        meinv.name = 'xiaomao';
        meinv.age = 19;
        meinv.sex = 'woman';
        meinv.sayHi = function ({
            alert('Hello~');
        }
        // Call the object. Property = value
Copy the code

Constructor method

Constructors must begin with a capital letter

       function Person(name, age, sex{
this.name = name;
this.age = age;
this.sex = sex;
this.sayHi = function({
alert('My name is:' + this.name + ', age: + this.age + ', gender: ' + this.sex); }}var xiaomao = new Person('xiaomao'.19.'woman');
var xiaohe = new Person('小何'.21.'male');
console.log(xiaohe.name);
console.log(xiaomao.name);
Copy the code

The New keyword executes four parts

  1. Creates a new empty object in memory.

  2. Let this point to the new object.

  3. Execute the code inside the constructor to add properties and methods to the new object.

  4. Return this new object.

    Object traversal

    for(variableinObject name) {// code
    }
    Copy the code

    Javascript built-in objects

    Built-in objects refer to objects that come with THE JS language. These objects are used by developers and provide some common or basic and necessary functions (properties and methods).

    The biggest advantage of built-in objects is rapid development.

    For example, Math, Date, Array, and String

    The Math object

    Math is not a constructor, but it has properties and methods

    methods

            Math.PI / / PI
            Math.floor() // Round down, take out the decimal part as you go down
            Math.ceil() // round up, round up
            Math.round() // The rounded version of the nearest round note that the result is -3.5
            Math.abs() // Absolute value, there is an implicit conversion - the string is converted to a number and then the absolute value is taken
            Math.max() / Math.min() // Find the maximum and minimum values
            Math.random();// Return a random decimal with values in the range [0, 1], 0 <= x < 1
    Copy the code

    Exercise – taking random numbers
    return Math.floor(Math.random() * (max - min + 1)) + min; 
    Copy the code

    The date object

    Is a constructor that can only be used after the function is instantiated

    Get the current time
    var now = new Date(a);console.log(now);//Date Sun Jan 17 2021 10:14:24 GMT+0800
    Copy the code
    Date () parameters

    * Returns the current time if there are no arguments

    * If there is an argument, return the argument time (numeric, comma, string ‘2020-1-178:8:8’)

    Time formatting

    Exercises – Output in a specific time format
var now = new Date(); //console.log(now); //Date Sun Jan 17 2021 10:14:24 GMT+0800 var year=now.getFullYear(); / var/year Month = now, getMonth (); / var/month date = now. GetDate (); / / day var arr = [' Sunday ', 'on Monday, Tuesday, Wednesday,' ', 'Thursday', 'Friday,' Saturday]; var day=now.getDay(); / / week for the console. The log (" today is "+ year +" years "+ Month + + date + ', '+' in ' ' '+ arr [day]);Copy the code
The time stamp

Obtaining method:

Start time: January 1, 1970

​ 1.valueOf()

​ 2.getTime()

​ 3.Var date1=+new Date();

4.H5 new method: date.now ();


Seckill countdown
<script>
        // The timestamp converts the time format
        //d = parseInt(total seconds / 60/60/24); // Count the days
        // h = parseInt(total seconds / 60/60% 24) // Count hours
        //m = parseInt(total seconds /60 %60); // Calculate the score
        //s = parseInt(total seconds %60); // Count the current number of seconds
        function cutdown(time{
            var nowTime = +new Date(a);// The current timestamp
            var inputTime = +new Date(time);// Enter the timestamp
            var chatime = (inputTime - nowTime) / 1000;// Timestamp difference ----> change to seconds
            var d = parseInt(chatime / 60 / 60 / 24); // Count the days
            d=d<10?'0'+d:d;
            var h = parseInt(chatime / 60 / 60 % 24// Count the hours
            h=h<10?'0'+h:h;
            var m = parseInt(chatime / 60 % 60); // Calculate the score
            m=m<10?'0'+m:m
            var s = parseInt(chatime % 60); // Count the current number of seconds
            s=s<10? s+'0':s;
            return d+'day'+h+'when'+m+'points'+s+'秒';
        }
        console.log(cutdown('the 2021-1-17 12:00:00'));
    </script>
Copy the code

The array object

Array object creation

1. Literal

2.New Array()

Array judgment method

1.instanceOf()

2.isArray()

Common operations on arrays

Array sort method

Sort () is used

       var arr = [1.64.9.6];
        arr.sort(function (a, b{
            return b - a; / / a sequence
            // return a - b; / / ascending
        });
        console.log(arr);
Copy the code

Array index method

Exercise – Array de-duplication
function unique(arr){ var newArr=[]; for(var i=0; i<arr.length; I++) {if (newArr. IndexOf (arr) [I] = = 1) {/ / not -- newArr deposit to the new array. Push (arr [I]); } } return newArr; } var demo=unique(['a','b','c','d','b','c','b']); console.log(demo);Copy the code

Array to string

Array interception, join and other methods

String object

String object characteristics

String has the length attribute -> Basic wrapper type: Wraps simple data types into complex data types

String\number\Boolean are both wrapper types ==== reference types

String immutability: Reassigning to change content reopens memory and forbids the activity of concatenating large numbers of strings

* string all operations do not change the string —-> all returns a new array to open a new space

Return position method by character

Exercise – Returns the number of repeated characters
<script> var str='abcdefghaaabcdef'; var index=str.indexOf('a'); Var num=0; While (index! Console. log(index) = 1){// if the index is not -1, there are repeated characters. num++; Index = str.indexof ('a',index+1); } console.log(" the number of occurrences of a is: "+ num); </script>Copy the code
Exercise – Returns the most frequently occurring character in a string and the number of occurrences
var str="abcdefgaaaaaaakdfa"; Var obj={}; var obj={}; for(var i=0; i<str.length; i++){ var chars=str.charAt(i); If (obj[chars]){obj[chars]++; }else{ obj[chars]=1; } } console.log(obj); Var Max =0; var cha=''; For (var key in obj){if(obj[key]> Max){Max =obj[key]; cha=key; } } //console.log(max); Console. log(" The most common character in the string is "+cha+", which is "+ Max ");Copy the code

Returns character methods by position

Basic string manipulation methods

String substitution split method

The Replace() method is used to Replace some characters with other characters in a string.

Split string into array, return a new array text end, thank you for watching. I wrote this column on the one hand because it is easy to refer to in the review process, on the other hand, of course, I want to record the learning, because it is worth it. At this moment, I want to start again

Remember when entering the campus unfocused, walked all the people think that a lot of detours, until April 2019, I finally begin to learn calm down, though a little late but now he had been on the review, and also received a little achievement ~ years later I will set foot on a new journey but will not stop learning (Ps: before the so-called blind mixed always also!) However, I never regret that I did a lot of actions unrelated to learning before, and there was no big gain but growth!

I will arrange the review content in the later stage and publish it in turn. Remember to pay attention to me for more information. There are also some materials written in Word, and you can contact me to obtain them if necessary

Finally, to use the words of a good friend of mine to encourage myself and others who have been confused like me ->A long way, you can, as long as you do, always succeed!

All the friends who have problems in study and life can poke at xiaomao ha. I really have gone through many detours. I hope I can help you as much as I can and warn you who are still confused

Thank you: some of the pictures in the article are from ‘Black Horse Programmer’s PPT’, I was too lazy to watermark!

The rest are original, reproduced please stamp me!

Scan code contact xiaomao students !!!! Little cute please poke me ~~

Please scan the code to follow my official account for learning materials.Punch in and flush !!!!

Remember to pay attention to me, please take care of me