JavaScript foundation details

Summary

1. What is JavaScript

  JS is a scripting language, an object-oriented language based on objects, or an interpretive language. Its basic structure is similar to other programming languages, such as C and VB, but it needs to be compiled before execution. It supports the development of client and server applications and components.

2. Basic components of JavaScript


Note: the latest version of ECMScript has reached esc, but most browsers are still in es5

Introducing JavaScript

1. Internal label introduction

<script  type="text/javascript">
    alert('hello,world');
</script>

Note: both body and head can be stored. type="text/javascript" unnecessary, default.

2. External introduction

<script src="js/qj.js"></script>

Note: Script tags must exist in pairs.

Basic syntax of JavaScript

1. Define variables

Variable type variable name = variable value;
var score = 71;

Note: JavaScript is strictly case sensitive!

2. Print variables

console.log(score) prints variables in the browser's console!

3. Output on the page

alert(num);

4. Define objects

<script>
    var person = {
        name: "qinjiang",
        age: 3,
        tags: ['js','java','web','...']
    }
</script>

Be careful:
The object is a brace;
Array is bracketed ~ ~ each property is separated by commas, the last one does not need to be added.
Java values must be objects of the same type, which is not required in JavaScript!
If the array subscript is out of bounds, undefined will be output

5. Different data types from Java

(1)number
JavaScript doesn't distinguish between decimals and integers.

          123 //Integer 123
          123.1 // Floating point 123.1
          1.123e3 //Scientific counting
          -99    //complex
          NaN    // not  a  number
          Infinity //Infinity

Note: try to avoid using floating-point numbers for calculation, there are precision problems!
(2) Comparison operator

           =
           ==Equal to (different types and values will be judged as true)
           ===Absolute equal (same type, same value, true result)

Be careful:
Nan = = Nan, this is not equal to all values, including yourself
Whether this number is NaN can only be determined by isNaN(NaN)

6. Strictly check the format: 'use strict'; prevent some problems caused by the randomness of JavaScript

<script>
    'use strict';
    let dh = 1;
</script>

Note: it must be written in the first line of JavaScript! let is recommended to define local variables

function

1. Define function

(1) mode 1

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

Note: if return is not executed, the result will be returned after the function is executed. The result is undefined
(2) mode two

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

Note: function(x) { This is an anonymous function. But you can assign the result to ABS. You can call the function through abs!

2. Suppose there is no parameter, how to avoid it?

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

3.arguments: a JS free keyword

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

4. The problem of multiple parameters: obtain all parameters except those already defined

<script>
    function aaa(a,b,...rest) {
        console.log("a=>"+a);
        console.log("b=>"+b);
        console.log(rest);
    }
    aaa()
</script>

Note: the rest parameter can only be written at the end. You must use Identification.

Scope of variable

1. If it is declared in the function body, it cannot be used outside the function body (if you want to implement it, you can study closure later)

function qj() {
    var x = 1;
    x = x + 1;
}
x = x + 2; //Uncaught ReferenceError: x is not defined

2. If two functions use the same variable name, as long as it is inside the function, there is no conflict

function qj() {
    var x = 1;
    x = x + 1;
}

function qj2() {
    var x = 'A';
    x = x + 1;
}

3. Internal functions can access members of external functions, otherwise, they cannot

function qj() {
    var x = 1;
    // Internal functions can access members of external functions, otherwise they cannot
    function qj2() {
        var y = x + 1;  // 2
    }
    var z = y + 1; // Uncaught ReferenceError: y is not defined
}

4. Hypothesis, internal function variable and external function variable, duplicate name!

<script>
    function qj() {
        var x = 1;
        function qj2() {
            var x = 'A';
            console.log('inner'+x); // outer1
        }
        console.log('outer'+x); //innerA
        qj2()
    }
    qj()
</script>

Note: function search variables in JavaScript start from their own functions ~, and search from 'inside' to 'outside'. If there is a function variable with the same name outside, the internal function will shield the variables of the external function.

5. Scope of promotion variable

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

The result is: xundefinited

6. The JS execution engine automatically promotes the declaration of Y, but does not enhance the assignment of variable y
function qj2() {
    var y;

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

7. Global function

(1) Global object window

var x = 'xxx';
alert(x);
alert(window.x); // By default, all global variables are automatically bound to the window object;

(2)alert() is also a window variable;

<script>
    var x = 'xxx';
    window.alert(x);
    var old_alert = window.alert;
    //old_alert(x);
    window.alert = function () {
    };
    // Found that alert() failed
    window.alert(123);
    //recovery
    window.alert =  old_alert;
    window.alert(456);
</script>

Note: Javascript actually has only one global scope. Any variable (function can also be regarded as a variable) that is not found in the scope of the function will be searched out. If it is not found in the global scope, an error is reported
(3) Problem: the result of local scope var is out of range and is still calculated

function aaa() {
    for (var i = 0; i < 100; i++) {
        console.log(i)
    }
    console.log(i+1); //Question? i out of this scope, you can also use
}

Solution: let keyword

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

8. const

(1) General definition constant

var PI = '3.14';
console.log(PI);
PI = '213'; //This value can be changed
console.log(PI);

(2) const in ES6

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

Note: the definition of const cannot be changed. It can be assigned before ES6.

Methods and properties

Mainly JavaScript can control the direction of this (through apply)

<script>
    function getAge() {
        // Year - year of birth
        var now = new Date().getFullYear();
        return now-this.bitrh;
    }
    var kuangshen = {
        name: 'Qin Jiang',
        bitrh: 2000,
        age: getAge
    };
    // kuangshen.age() ok
    getAge.apply(kuangshen,[]);// this, pointing to kuangshen, null parameter
</script>

Internal objects

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

Basic use of Date

<script>
    var now = new Date(); //Sat Jan 04 2020 10:47:06 GMT+0800 (China standard time)
    now.getFullYear(); //year
    now.getMonth(); // Month 0-11 represents month
    now.getDate(); // day
    now.getDay(); // What day is it
    now.getHours(); // Time
    now.getMinutes(); // branch
    now.getSeconds(); // second
    now.getTime(); // Timestamps in 1970 1.1 0:00:00 milliseconds
    console.log(new Date(1578106175991)) //Time stamp to time
    now.toLocaleString()           "2020/1/4 10 a.m.:49:35"
    now.toGMTString()              "Sat, 04 Jan 2020 02:49:35 GMT"
</script>

JSON

1. What is JSON

  • JSON (JavaScript object notation) is a lightweight data exchange format.
  • The simple and clear hierarchy makes JSON an ideal data exchange language.
  • It is easy for people to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.

2.JSON format

  • Objects use {}
  • Array uses []
  • It is easy for people to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.

For example: conversion of JSON string and JS object

var user = {
    name: "qinjiang",
    age: 3,
    sex: 'male'
}
//Object to json string {"name":"qinjiang","age":3,"sex": "male"}
var jsonUser =  JSON.stringify(user);
//Convert json string to object parameter to json string
var obj = JSON.parse('{"name":"qinjiang","age":3,"sex":"male"}');
Published 26 original articles, won praise 16, visited 712
Private letter follow

Keywords: Javascript JSON Java REST

Added by mgason on Tue, 04 Feb 2020 07:04:53 +0200