030_JavaScript

Time:2021-9-15

catalogue

Front end knowledge system

image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png

What is JavaScript

JavaScript is the most popular scripting language in the world.
ECMAScript can be understood as a standard of JavaScript.
Latest version ES6.
However, most browsers only stay on supporting Es5 code.
The versions of development environment and production environment are inconsistent.

quick get start

Introducing JavaScript

  1. Internal label
  2. External introduction
Title

    
    
        // alert('hello,world');
alert('hello,world');

Introduction to basic grammar

Title

    
        //1. Define variable type variable name = variable value;
        var num = 1;
        //2. Condition control
        alert(num);
        if (2>1) {
            alert("true");
        }
        //3. Print variables in the browser console
        console.log(num);

data type

Number number

JS does not distinguish between integers and decimals

123 // integer
123
123.1 // floating point number
123.1
1.231e2 // scientific counting
123.1
-123 // negative number
-123
NaN // not a number
NaN
Infinity // indicates infinity
Infinity

String string

'abc'
"abc"
"abc"
"abc"

Boolean Boolean

console.log(2>1)
VM520:1 true
console.log(2<1)
VM568:1 false

Null to null

Undefined undefined

Symbol unique value

Symbol is a new raw data type introduced by ES6 to represent unique values.

Array array

var arr = [1,2,3,4,'ab',null,true];
new Array(1,2,3,4,'ab',null,true);
console.log(arr[2]);

Object object

var person = {
  name:'zhangyq',
  age:18,
  tags:['java','js','web']
}
console.log(person.age);

Function function

Strict check mode strict

/*
Premise: idea needs to be set to support ES6 syntax
'use strict'; Strictly check the mode to prevent some problems caused by the randomness of JavaScript
It must be written on the first line of JavaScript
It is recommended to use let to define local variables, such as let I = 1;
*/
//Strictly check the mode strict. In the strict addition mode, I = 1 reports an error
'use strict';
//Global variable
//i = 1;

Idea settings support ES6 syntax
image.png

data type

character string

'use strict';
//1. Normal strings are wrapped in single quotation marks or double quotation marks
console.log('a');
console.log("a");
//2. Pay attention to escape characters
console.log('a\'');
console.log("a\'");
console.log('a\nb');
console.log('\u4e2d'); // Unicode
console.log('\x41'); // Ascll
//3. Write multi line string with backquotes`
var msg = `hello
world
Hello;
console.log(msg);
//4. Template string, using backquotes ` and$
let name='zhangyq';
console.log(`nihao,${name}`);

array

//An array can contain any data type
var arr=[0,1,2,3,4,5];
//Slice() intercepts a part of the array and returns a new array
var arr1=arr.slice(3);
//Push () into the tail
arr.push('a','b');
//Pop() pops up the last
arr.pop();
//Press unshift() into the head
arr.unshift('a','b');
// shift();  Pop up first
arr.shift();
//Sort() sort
var arr=['B','C','A'];
arr.sort();
console.log(arr);
//Reverse() reverse
arr.reverse();
console.log(arr);
//Concat() concatenation returns a new array without changing the original array
var arr2=arr.concat([1,2,3]);
console.log(arr2);
console.log(arr);
//Join() prints a concatenated array, concatenated with a specific string
console.log(arr.join('-'));
//Multidimensional array
var arr=[[1,2],[3,4],['a','b']];

object

var person={
  name:"zhangyq",
  age:18,
  phone:"13299998888"
}
person.name="zhangsf";
//Delete object properties
delete person.name
//Add object properties
person.email="[email protected]"
//Determine whether the property is in this object
'age' in person
//Determine whether the method is in this object
'toString' in person
Determine whether the property or method is owned by itself
person.hasOwnProperty('age');
person.hasOwnProperty('toString');

Process control

  1. If judgment
  2. while Loop
  3. For loop
  4. Foreach loop
  5. for…in
  6. for…of
//Foreach loop
var arr=[1,2,2,3,4,5];
arr.forEach(function(value){
  console.log(value);
});
//The value of for... In is the index
for(var index in arr){
  console.log(arr[index]);
}
//The for... Of loop is a concrete value
for(var v of arr){
  console.log(v);
}

New features of map and set ES6

//Map
var map=new Map([['tom',100],['jack',90],['join',80]]);
var name=map.get('tom');
map.set('admin',123);
map.delete('admin');
//Set unordered non repeating set
var set=new Set([1,2,2,3,3]); //  Set can be de duplicated
set.add(4);
set.delete(1);
console.log(set.has(2)); //  Include an element

function

Define function

  1. Definition method I
//Once executed, return represents the end of the function and returns the result!
//If return is not executed, the result will also be returned after the function is executed. The result is undefined.
function abs(x){
  if(x>=0){
    return x;
  }else{
    return -x;
  }
}
abs(-10);
  1. Definition mode 2
//Function (x) {...} is an anonymous function, which can be called through abs!
var abs=function(x){
  if(x>=0){
    return x;
  }else{
    return -x;
  }
}
abs(-10);

JavaScript can pass any parameter or not!

var abs=function(x){
  //Throw exception manually
  if(typeof x !== 'number'){
    throw 'Not a Number';
  }
  if(x>=0){
    return x;
  }else{
    return -x;
  }
}

arguments

  1. Arguments represents all parameters and is an array
var abs=function(x){
  if(arguments.length=1){
    return x;
  }else if(arguments.length>1){
    return arguments.length;
  }
}

rest

  1. A new feature introduced in ES6 to obtain all parameters except those already defined
  2. The rest parameter can only be written at the end and must be identified with
function fun(a,b,...rest){
  console.log("a->"+a);
  console.log("b->"+b);
  console.log(rest);
}

Scope of variable

  1. The variables declared in the function body cannot be used outside the function body (if you want to implement them, you can study the lower closure)
function fun(){
  var x=1;
  x=x+1;
}
x=x+2; // Uncaught ReferenceError: x is not defined
  1. Internal functions can access variables of external functions, and vice versa
function funA(){
  var x=1;
  function funB(){
    var y=x+1;
  }
  var z=y+1; // Uncaught ReferenceError: y is not defined
}
  1. Global variables: defined outside functions
var x=1;
function f(){
  console.log(x);
}
console.log(x);
  1. Global object window: by default, all global variables will be automatically bound under the window object
var x=1;
console.log("x->"+x);
console.log("window.x->"+window.x);
  1. JavaScript actually has only one global scope, and any variable (a function can also be regarded as a variable). If it is not found within the scope of the function, it will look outward until the global scope window is not found, and an error will be reported
  2. Since all global variables are bound to window, if different JS files use the same global variables, they will conflict. How to reduce the conflict? Put all your code into the unique space name defined by yourself to reduce the problem of global naming conflict
//Unique global variable
var main={};

//Define global variables
main.name='zhangyq';
main.add=function(a,b){
  return a+b;
}

Let local variable declaration

function f(){
  for(var i=0;i<100;i++){
    console.log(i);
  }
  console.log(i+1); //  101 question? I out of the scope, you can also use
}

ES6 let keyword to solve the problem of local scope!

function f(){
  for(let i=0;i<100;i++){
    console.log(i);
  }
  console.log(i+1); // Uncaught ReferenceError: i is not defined
}

It is recommended to use let to define locally scoped variables

Const constants declare read-only variables

const PI=3.14; //  read-only variable 
console.log(PI);
pi=3.15; // TypeError: Assignment to constant variable

method

  1. The method is to put the function in the object
var qing={
  name:'zhangyq',
  birth:2000,
  age:function(){
    var now=new Date().gerFullYear();
    return now-this.birth;
  }
}
qing.name;
qing.age();
  1. Apply specifies the object that calls the method

Internal object

Date

Method self inspection

Json

JSON(JavaScript  Object notation (JS object notation) is a lightweight data exchange format.

Var user = {Name: "zhangyq", age: 18, sex: 'male'}
//Object to JSON string
var jsonStr=JSON.stringify(user);
//Object {Name: "zhangyq", age: 18, sex: "male"}
//JSON string {"name": "zhangyq", "age": 18, "sex": "male"}
//Convert JSON string to object
var obj=JSON.parse(jsonStr);

object-oriented programming

Prototype inheritance

Var user = {Name: "zhangyq", age: 18, sex: 'male'}
var xiaoming={name:"xiaoming"}
//Xiaoming's prototype is user
xiaoming.__proto__=user
/*xiaoming
{name: "xiaoming"}
name: "xiaoming"
__proto__:
age: 18
name: "zhangyq"
Sex: "male"
__proto__: Object
*/

Class inheritance

The class keyword is introduced in ES6

//Define a class, property, method
class Student{
  constructor(name){
    this.name=name;
  }
  hello(){
    alert('hello');
  }
}

var xiaoming=new Student('xiaoming');
var xiaohong=new Student('xiaohong');
//Inherit
class XiaoStudent{
  constructor(name,grade){
    super(name);
    this.grade=grade;
  }
  myGrade(){
    Alert ('I am a pupil ');
  }
}

Manipulate BOM objects

  1. Browser introduction
    1. IE6~11
    2. Chrome
    3. Safari
    4. FireFox
  2. Window stands for browser window
window.alert(1)
window.innerHeight
window.outerHeight
  1. Navigator encapsulates the information of the browser
  2. Screen stands for screen
screen.width
screen.height
  1. Location represents the URL information of the current page
location
//Refresh page
location.reload()
//Jump page
location.assign('www.baidu.com');
  1. Document represents the current page
document.title
Document. Title = 'my page'
//Get cookie
document.cookie
  1. History stands for browser history
history.back()
history.forward()

Manipulating DOM objects

DOM document object model
A web browser is a DOM tree structure

Title I
  p1
  p2
//Query by tag name
var h1Array=document.getElementsByTagName('h1');
//Query by ID
var p1=document.getElementById('p1');
//Query by class name
var p2Array=document.getElementsByClassName('p2');
var div1=document.getElementById('div1');
//Get child nodes
var childrens=div1.children;

//Modify text value
p1.innerText='123';
//Modify HTML
p1.innerHTML='123';
//Modify CSS Style
p1.style.color='red';

//To delete a node, you can only delete child nodes through the parent node
div1.removeChild(p1);
p1.parentElement.removeChild(p1);
div1.removeChild(div1.children[2]);
div1.removeChild(div1.children[1]);
div1.removeChild(div1.children[0]);

//Append existing tags
div1.appendChild(p2);
//Create label and append
var p4=document.createElement('p');
p4.id='p4';
p4.innerText='p4';
p4.setAttribute('class','p2');
div1.appendChild(p4);
//Insert P2 node before P1
div1.insertBefore(p2,p1);

Operation form (MD5 encryption password)

user name 
  password 
  
  Submit
//Get input
var input_username=document.getElementById('username');
//Get input的值
var username=input_username.value;
//Modify the value of input
input_username.value='zhangyq';

function submit(){
  var username=document.getElementById('username').value;
  var password=document.getElementById('password').value;
  console.log(username);
  console.log(password);
  //MD5 encryption password
  md5_password=md5(password);
  console.log(md5_password);
  document.getElementById('md5_password').value=md5_password;
}

jQuery

The jQuery library encapsulates a large number of JavaScript functions

Download Reference jQuery Library

Download:https://jquery.com

Formula $(selector). Action()

$('#a1').click(function(){
  alert('hello');
});

JQuery vs JavaScript

//JavaScript
document.getElementsByTagName();
document.getElementById();
document.getElementsByClassName();

//All selectors in jQuery CSS can be used, such as hierarchy selector, pseudo class selector, attribute selector, etc
$('p').click();
$('#id').click();
$('.class').click();

event

  1. Mouse event
  2. Keyboard events
  3. Other events

image.png

#divMove{
    width: 500px;
    height: 500px;
    border: 1px solid red;
  }


mouse: 
Move the mouse here


  //Respond to the event when the web page element is loaded
  //$(document).ready(function(){});
  //Can be simplified to
  $(function(){
    $('#divMove').mousemove(function(e){
      $('#mouseMove').text('x:'+e.pageX+'y:'+e.pageY);
    });
  });

Manipulating DOM elements

$('#test_ul li[name=python]').text();
$('#test_ul li[name=python]').html();
$('#test_ul li[name=python]').css({"color":"#ff0011","background":"blue"});
$('#test_ul li[name=python]').css("color","#ff0011");
$('#test_ul li[name=python]').css("color");
$('#test_ul li[name=python]').hide();
$('#test_ul li[name=python]').show();
$('#test_ul li[name=python]').toggle();
$(window).width();
$(window).height();

JQuery Chinese document:https://jquery.cuishifeng.cn/

antic

Consolidate JS, look at jQuery source code, look at small game source code – source code home

Source code house:https://www.mycodes.net/

Consolidate the HTML / CSS raking website, down and modify it accordingly to see the effect

Steps for picking up websites:

  1. Open the website, select elements, select the code, and press Delete to delete. It will not affect the page to continue deletion, affect the page to go back, and delete the next line until there is no deletion.

image.png

  1. Right click Copy – > copy outerhtml, copy the code, paste the code into your own HTML file, and modify the corresponding HTML and CSS.

image.png