Getting started with JavaScript

Time:2021-11-25

JavaScript

JavaScript is a scripting language

ECMAScript can be understood as a standard of JavaScript
The latest version has reached ES6~
However, most browsers only support Es5 code!
Development environment - online environment, version inconsistency

quick get start

Introducing JavaScript

1. Internal label

<script type="text/javascript"></script>

2. External label

<!-- External import -- >
<!-- Note: script must appear in pairs -- >
<script src="js/first.js"></script>

Basic grammar

<script>
        //JavaScript is strictly case sensitive
        //1. Define variables
        let score = 71;
        // let zz = 2;
        // alert(num)
        //2. Condition control
        if (score>60 && score<70){
            alert("60~70")
        }else if (score>70 && score<80){
            alert("70~80")
        }else {
            alert("other")
        }
        //Console.log (score) prints variables in the browser console
        /**
         */

    </script>

data type

Values, text, graphics, audio, video…

JS does not distinguish between decimal and integer

variable

Cannot start with a number

number

//Integer 123
//Floating point number 123.1
//Scientific counting 1.123e3
//Negative number - 99
//NaN not a number
//Represents infinity

character string

// 'abc' "abc"

Boolean value

//true false

Logical operation

//&&Both are true, the result is true | one is true, the result is true! True is false, false is true

Comparison operator

//=Assignment
//= = equal to (if the type is different and the value is the same, it will also be judged as true)
//===Absolutely equal to (the same type, the same value, and the result is true)
  • Notice:
    //Nan = = = Nan, which is not equal to all values, including itself
    //You can only judge whether this number is Nan by IsNaN (Nan)

    Floating point problem

    console.log((1/3) === (1-2/3))
    //The result is false

    Try to avoid using floating-point numbers for operation, which has accuracy problems!

    Math.abs(1/3-(1-2/3))<0.0000001
    //Generally, if it is established in this way, it is considered equal

Null and nudefined

Null null
Undefined undefined

array

The array of Java is a series of objects of the same type, which is not required by JavaScript

//To ensure the readability of the code, try to use []
let arr = [1,2,true,3,4,5,'hello',null]
new Array(1,2,true,3,4,5,'hello',null)

Take array subscript: if it is out of bounds, it will

undefined

object

Objects are braces and arrays are brackets
Each attribute is separated by commas, and the last one does not need to be added

let person = {
            name:"hudu",
            age:3,
            tags:['java','js','web','...']
        }

Get the value of the object

person.name
> hudu
person.age
> 30

Strict check format

<!--
'use strict'
Premise: idea needs to support ES6 syntax
It is recommended to use let to define local variables~
-->
<script>
    //Strict check mode, strict check mode, to prevent some problems caused by the randomness of JavaScript
    //It must be written on the first line of JavaScript
    'use strict'
    //Global variable
    let i = 1;
    //ES6 let
</script>

data type

character string

1. Normal strings are wrapped in single quotation marks or double quotation marks

2. Note escape characters

\'
\n
\t
\U4e2d \ u##### Unicode characters
\X41 ascll character

3. Multiline string

let msg = `hello
        world
        Hello
        hi~`;

4. Template string

let name = 'hudu';
let age = 3;
Let msg2 = ` Hello, ${name} ';

5. String length

let student = 'student';
console.log(student.length)

6. String variability: immutable
7. Uppercase conversion

//Note that this is a method, not a property
student.toUpperCase()
student.toLowerCase()
Student. Indexof ('t ') // get the specified character position
Student. Substring (2) // from the second to the last, the two parameters represent the number from the first to the second, closed on the left and open on the right

array

Slice() intercepts part of the array and returns a new array
Push() pop() tail
Unshitf() press in the head and shitf() eject the head
sort()
reverse()
Arr.concat ([1,2,3]) returns a new array
Join ('-') prints a spliced array, concatenated with a specific string
Multidimensional array
arr[[1,2],[3,4]]

object

Several key value pairs
All keys in JavaScript are strings with arbitrary values

1. Object assignment
 2. No error will be reported when using non-existent attributes. Undefined
 3. Dynamic deletion attribute delete person.name
 4. Dynamically add attribute person. Email = ' [email protected] 'add a value directly to the attribute
 5. Determine whether the attribute is' age 'in person in this object
 6. Determine whether the property is the hasownproperty owned by the object itself

Process control

if(){}else if(){}else{}

while()
do{}while()

for()
For (VaR num in age) {} num is the index
For (VaR num of age) {} num is the specific value

forEach(function(value){})

Map and set

<script>
    'use strict'
    let map = new Map([['tom',99],['jack',80],['alex',90]]);
    let msg = map.get('alex');
    console.log(msg);
    map.set('admin',123);
</script>

Set: unordered and non duplicate sets

<script>
    'use strict'
    let set = new Set([3,1,1,1,1,1]);
    set.add(2);
    set.delete(1);
    console.log(set.has(3));
    console.log(Array.from(set));
</script>

iterator

for(let i of map)

function

definition

function abs(x){
    if(x>=0){
        return x;
    }else{
        return -x;
    }
}

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

Arguments is a JS free keyword;
Represents that all parameters passed in are an array!
//Rest can only be written at the end
//Gets all parameters except those already defined
function aaa(a,b,...rest){
    console.log("a>"+a);
    console.log(rest);
}

Variable scope

function qj() {
    var x="x"+y
    console.1og(x);
    var y='y';
}

Result: xundefined
Note: JS execution engine automatically promotes the declaration of Y, but does not promote the assignment of variable y;

function qj2(){
    var y;
    var x = "x"+y;
    console.log(x);
    y = 'y';
}

This is a feature that existed at the beginning of JavaScript. Develop norms: all variable definitions are placed at the head of the function. Do not misplace them to facilitate code maintenance;

Global function

Global object window

var x='xxx';
alert(x);
alert(window.x); // By default, all objects are bound to window objects

The alter () function itself is a window variable
var x='xхх';
window.alert(x);
var old_alert = window.alert;
//o1d_alert(x);
window.alert = function (){
};
//Alert() was found invalid
window.alert(123);
//Restore
window.alert =old_alert;
window.alert(456) ;

JavaScript actually has only one global scope. If any variable (function can also be regarded as a variable) is not found within the scope of the function, it will look outward. If it is not found in the global scope, an error will be reportedReferenceError

standard

Since all global variables are bound to the window, if different JS files use the same global variables, conflicts – > how to reduce conflicts

//Unique global variable
let huduapp = {};

//Define globally unique variables
huduapp.name = "hudu";
huduapp.add = function (a,b) {
    return a+b;
}

Put all your code in the user-defined unique space name to reduce the problem of global naming conflict

Local scope let

function aaa() {
    for (var i = 0;i<100;i++){
    // for (let i = 0;i<100;i++){
        console.log(i)
    }
    console.log(i+1);// You can also use VaR I to get out of this scope
}

Constant const

read-only variable

var PI = '3.14';
console.log(PI);
PI='123';// You can change this value
console.log(PI);


This constant const is introduced in ES6
const PI='3.14';// Read only constant
console.log(PI);
PI='123';

method

Definition method

Method is to put the function in the object. The object has only two things: attributes and methods

<script>
    let hudu = {
        name:'hudu',
        birth:1990,
        age:function () {
            let now = new Date().getFullYear();
            return now - this.birth;
        }
    }
</script>

What does this stand for

function getAge(){
    let now = new Date().getFullYear();
    return now - this.birth;
}

let hudu = {
    name:'hudu',
    birth:1990,
    age: getAge
}

This cannot be pointed to. It is the object that calls it by default;

apply

You can control the direction of this in JS

Getage. Apply (hudu, []) // this points to the hudu object. The parameter is null

Internal object

Standard object

typeof 123
"number"
typeof '123'
"string"
typeof true
"boolean"
typeof NaN
"number"
typeof []
"object"
typeof {}
"object"
typeof Math.abs
"function"
typeof undefined
"undefined"

Date

Basic use

let date = new Date();//Sun Jul 05 2020 12:49:42 GMT+0800 (China Standard Time)
date.getFullYear();// particular year
date.getMonth();// Month 0 ~ 11
date.getDate();// day
date.getDay();// What day is today?
date.getHours();// hour
date.getMinutes();
date.getSeconds();
date.getTime();// time stamp

Console.log (new date (1593924582331)) // convert timestamp to time

date.toLocaleString();// Local time

JSON

format

  • All objects use {}

  • Arrays all use []

  • All key value pairs use key: value

    'use strict'
    let user = {
     name:'hudu',
     age:30,
     sex:'man'
    }
    //Object to JSON string, {"name": "hudu", "age": 30, "sex": "man"}
    let json_user = JSON.stringify(user)
    //The JSON string is converted to an object, and the parameters are JSON strings
    let obj = JSON.parse('{"name":"hudu","age":30,"sex":"man"}');

    Differences between JSON strings and JSON objects

    var obj = {a:'helloa',b:'hellob'}
    let json = '{"a":"hello","b":"hellob"}';

Ajax

  • Native JS writing XHR asynchronous request
  • JQuery encapsulated method ${“#name”}. Ajax (“”)
  • Axios request

object-oriented programming

What is an object

In Java

Classes: Templates

Objects: concrete instances

In JavaScript

Classes: prototype objects

Objects: concrete instances

let student = {
    name:'hudu',
    age:20,
    run:function () {
        console.log(this.name+"run...")
    }
}

let xiaoming = {
    name:'xiaoming'
}

//Xiao Ming's prototype is student
//Prototype object
xiaoming.__proto__ = student;

Class inheritance

classKeywords are introduced by ES6.

Define a class, property, method

<script>
    function Student(name) {
        this.name = name;
    }

    //Add a new method to the student
    Student.prototype.hello = function () {
        alert('Hello')
    }

    //After ES6
    //Define a student's class
    class student{
        constructor(name) {
            this.name = name;
        }
        hello(){
            alert('hello')
        }
    }
    let xiaoming = new Student('xiaoming');
</script>

inherit

class xiaoxue extends Student{
    constructor(name,grade) {
        super(name);
        this.grade = grade;
    }

    myGrade(){
        Alert ('I'm a pupil in class' + this. Grade +);
    }
}

let xiaohong = new xiaoxue('xiaohong',1)

Essence: viewing object prototypes

xiaohong
xiaoxue {name: "xiaohong", grade: 1}
grade: 1
name: "xiaohong"
__proto__: Student

Prototype chain

Operation BOM object (key)

BOM: Browser Object Models

window

Window stands for browser window

window.alert(1);
undefined
window.innerHeight
150
window.innerWidth
944
window.outerHeight
624
window.outerWidth
944

Navigator (not recommended)

Navigator encapsulates browser information

window.navigator.appCodeName
"Mozilla"
window.navigator.appName
"Netscape"
window.navigator.appVersion
"5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
navigator.platform
"MacIntel"

Most of the time, I won’t use itnavigarot, will be artificially modified

These attributes are not recommended for judging and writing code

screen

screen.width
1440
screen.height
810

location

Location represents the URL information of the current page

hash: ""
host: "www.baidu.com"
hostname: "www.baidu.com"
href: "https://www.baidu.com/"
origin: "https://www.baidu.com"
pathname: "/"
port: ""
protocol: "https:"
Reload: reload() // refresh the web page

//Set new address
location.assign('https://www.bilibili.com/')

document

Document represents the current page, HTML DOM document tree

document.title
"Beep beep (゜ - ゜) cheers ~-bilibilibili"
document.title = 'hudu'

Get the specific document tree node

<dl id="app">
    <dt>Java</dt>
    <dd>JavaSE</dd>
    <dd>JavaEE</dd>
</dl>

<script>
    let dl = document.getElementById('app')
</script>

Get cookie

document.cookie
""

Principle of hijacking cookies
www.taobao.com

<script src="aaa.js">

</sript>

<!-- Malicious personnel; Get your cookie and upload it to his server ~ -- >

The server can set a cookie: httponly

history

Represents the history of the browser (not recommended)

history.forward()
history.back()

Manipulating DOM objects

DOM document object model

core

The browser web page is a DOM tree structure!

  • Update: updating DOM nodes
  • Traverse DOM node: get DOM node
  • Delete: deletes the DOM node
  • Add: add a new DOM node

To operate a DOM node, you do not need to obtain the DOM node

Get DOM node

//Label
let h1 = document.getElementsByTagName('h1');

let p1 = document.getElementById('p1');
let p2 = document.getElementsByClassName('p2');
let father = document.getElementById('father');

Let children = father. Children // get all child nodes under the parent node
father.lastChild;
father.firstChild;
p1.nextElementSibling;

This is the native code. After that, we try to use jQuery ();

Update node

<body>
<div id="id1">

</div>

<script>
    let id1 = document.getElementById('id1')
    id1.innerText = 123;
</script>
</body>

Operation text

  • id1.innerText = 123;Modify text value
  • id1.innerHTML = '<strong>12345</strong>'You can use very thin HTML text tags

Is an override operation

Operation JS

Id1. Style. Color = 'Red' // use string for attribute
Id1.style.fontsize = '20px' // underline hump naming

Delete node

To delete a node, first obtain the parent node, and then delete the node

<div id="father">
    <h1>Title I</h1>
    <p id="p1">p1</p>
    <p class="p2">p2</p>
</div>

<script>
    let father = document.getElementById('father');

    let self = document.getElementById(p1);
    let father1 = self.parentElement;
    father1.removeChild(self);

    // father.removeChild(p1);

</script>
father.children
HTMLCollection(3) [h1, p#p1, p.p2, p1: p#p1]
father.children[0]
<h1>Title I</h1>

Note: when deleting multiple nodes, children change from time to time. Be careful when deleting nodes

Insert node

We get a DOM node. Assuming that the DOM node is empty, we can add an element through innerText or innerHTML.

However, if the DOM node already has elements, we can’t do so, which will produce overrides

Append operation

<p id="js">Java</p>
<div id="list">
    <p id="se">JavaSE</p>
    <p id="ee">JavaEE</p>
    <p id="me">JavaME</p>
</div>

<script>
    let js = document.getElementById('js');
    let list = document.getElementById('list');


</script>

list.appendChild(js)
<p id="js">Java</p>

Create a new label

let js = document.getElementById('js');
let list = document.getElementById('list');

list.appendChild(js);// Append to

//Create a new node through JS
let newP = document.createElement('p');
// newP.setAttribute('id','newP');
newP.id = 'newP';
// newP.innerHTML = ''
newP.innerText = 'hello';
list.appendChild(newP);

//Create a label node (any value can be set through this property)
let myScript = document.createElement('script');
myScript.setAttribute('type','text/javascript')

//Set the background color for the body through the style mode
let body = document.getElementsByTagName('body');
// body[0].style.background = '#66ccff';

//By adding CSS
let myStyle = document.createElement('style');
myStyle.innerHTML = 'body{background-color:#66ccff;}';
let head = document.getElementsByTagName('head')[0];
head.appendChild(myStyle);

insertBefore

let ee = document.getElementById('ee');
let js = document.getElementById('js');
let list = document.getElementById('list');
//The node containing them, insertBefore (newnode, targetnode);
list.insertBefore(js,ee);

Operation form

<form action="">
    <p>
        <span>User name: < / span > < input type = "text" id = "username" >
    </p>
    <p>
        <span>Gender</span>
        < input type = "radio" name = "sex" value = "man" > male <-- checked="true"-->
        < input type = "radio" name = "sex" value = "woman" > female
    </p>

</form>

<script>
    let input_text = document.getElementById('username');
    // input_text.value='1231231';

    let man = document.getElementsByTagName('input')[1];
    let woman = document.getElementsByTagName('input')[2];

    //For radio, multiple boxes, etc., value can only get a value
    man.checked;// Check whether the returned result is true. True is selected
    // man.checked = true;// assignment
</script>

Submit Form

MD5 encryption password

<!--
Form binding submission event
Onsubmit binds a submit detection function true or false
This result is returned to the form and received using onsubmit
-->
<form action="#" method="post" onsubmit="return check()">
    <p>
        <span>User name: < / span > < input type = "text" required placeholder = "please enter user name" id = "username" name = "username" >
    </p>
    <p>
<!--        < Span > Secret & nbsp& nbsp;& nbsp;& nbsp; Code: < / span > < input type = "password" id = "password" name = "password" > -- >
        <span>Secret & nbsp& nbsp;& nbsp;& nbsp; Code: < / span > < input type = "password" id = "input password" >
    </p>
    <input type="hidden" id="md5-password" name="md5-password">
<!--    < Input type = "submit" value = "register" > -- >
<!--     Binding event onclick is clicked -- >
<!--    < Button type = "submit" onclick = "check()" > submit < / button > -- >
    < button type = "submit" > submit < / button >
</form>

<script>
    function check() {
        let username = document.getElementById('username');
        let password = document.getElementById('input-password');
        let md5pwd = document.getElementById('md5-password');

        md5pwd.value = md5(password.value);

        //You can verify and judge the form content. True means submit and false means fail
        return true;
        // console.log(username.value);
        // console.log(password.value);
        //// MD5 algorithm
        // // password.value = '********'
        // password.value = md5(password.value)
        // console.log(password.value);
    }
</script>

jQuery

<!--
Formula: $(selector). Action()
-->

< a href = "#" id = "test jQuery" > Click me</a>

<script>
    // let id = document.getElementById('test-jquery');
    // id.click();
    //Selectors are CSS selectors
    $('#test-jquery').click(function () {
        alert('hello,jquery')

    })
</script>

selector

<script>
document.getElementsByTagName();
document.getElementById();
document.getElementsByClassName();

// jQuery
$('p').click();
$('#id1').click();
$('.class1').click();

</script>

Document tool station:jquery.cuishifeng.cn/

event

Mouse events, keyboard events, other events

<!-- Get current mouse coordinates -- >
mouse:<span id="mouseMove"></span>
<div id="divMove">
Try moving the mouse here
</div>

<script>
    //When the web page element is loaded, respond to the event
    // $(document).ready(function () {
    //
    // })
    $(function () {
        $('#divMove').mousemove(function (e) {
            let x = e.pageX;
            let y = e.pageY;
            $('#mouseMove').text('x:'+x+'y:'+y);
            // console.log(e.pageX)
        })
    });
</script>

Operation DOM

// document.getElementsByClassName('js')
$('#test-ul li[class=python]').text();// Get value
$('#test-ul li[class=python]').text('hello');// Set value
$('#test-ul').html();

CSS operation

$('#test-ul li[class=python]').css("color","red");

Hiding and disappearing of elements

//Equivalent to display: None
$('#test-ul li[class=python]').show();
$('#test-ul li[class=python]').hide();

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]