JavaScript

JavaScript

1. Introduction to JavaScript

JavaScript is a front-end programming language called JS for short. What needs to be explained is that JS has nothing to do with java. js is also called ecmascript. The currently used version is 5.1.

Features:

  1. JS is a lightweight programming language
  2. JS can be executed by the browser after inserting HTML.

2. the syntax of JS

2.1 Notes

//Single line comment

/*Multi-line comment*/

2.2 The way to introduce to HTML

1. Write directly in the script tag

<script>//Write the code here</script>

2. Import external JS files through the script tag src

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

2.3 JS data type

2.3.1 Dynamic language and static language

JS is a dynamically typed language. What are dynamic and static types?

Features of dynamically typed languages:

Languages ​​that do data type checking during runtime, that is, when programming in a dynamically typed language, do not need to assign data types to any variables .

The language will record the data type internally when assigning a value to a variable for the first time, what data type the assigned value is, and what data type the variable is. Dynamically typed languages ​​include JavaScript, Python, PHP, etc.

Advantages: easy to read, no need to write a lot of type-related code;

Disadvantages: It is not convenient to debug, and if the naming is not standardized, it will cause incomprehension, which is not conducive to understanding.

Features of statically typed languages:

Check the data type of the variable during compilation, that is, when you define the variable, you need to declare what data type the variable is. The statically typed languages ​​are: C, C++, C#, JAVA, etc.

Advantages: The structure is very standardized, easy to debug, and convenient for type safety

Disadvantages: For this, more type-related code needs to be written, which is more complicated.

2.3.2 JS variable declaration

1. JS variable names can be composed of numbers, $, letters and underscores, and cannot start with a number.

2. When declaring variables, use var to declare global variables and let to declare local variables (let is a new variable declaration method added by ES6).

var a = 1;
undefined
let b = 2;
undefined
a
1
b
2

2.3.3 Terminator

JS uses a semicolon as the end of a sentence, and many places in JS are similar to c.

2.3.4number (number)

JS does not distinguish between integer and floating-point types, their data types are all number.

Used when there is no beginning of a number in a string. If you use parseint() to take out the data in the string, you will get the return value NaN. NaN means not a number.

var x1 ='abc123shfuis'
undefined
parseInt(x1);
NaN
var x2 = '123asd'
parseInt(x2);
123
var x3 ='asd123';
parseInt(x3);
NaN

parseInt gets the integer type of the data, and parseFloat gets the floating point type of the data.

x1 = '123.123';
parseInt(x1);
123
x1 = '123.123';
parseFloat(x1);
123.123

2.3.5 String

Commonly used string type built-in methods:

method

Description

.length

Return length

.trim()

Remove whitespace

.trimLeft()

Remove the left blank

.trimRight()

Remove the blank on the right

.charAt(n)

Returns the nth character

.concat(value, ...)

Splicing

.indexOf(substring, start)

Subsequence position

.substring(from, to)

Get subsequence based on index

.slice(start, end)

slice

.toLowerCase()

lower case

.toUpperCase()

capital

.split(delimiter, limit)

segmentation

Concatenation of strings:

The concatenation of strings can use the built-in method concat, or use the "+" sign, and the "+" sign is recommended here.

var x2 ='hello'
x3 ='World'
x2 + x3;
"helloWorld"
x2.concat(x3)
"helloWorld"

Remove the blanks at the front and back:

var x4 = 'millenni um'
x4.length
16
x4.trim()
"millenni um"
x4.trim('m')
"millenni um"

As you can see, the trim here can only clear blanks, not the letter elements at both ends, which is different from Python's strip.

Index value:

x5
"millenni um"
x5.charAt('1')
"i"
x5.indexOf('e')
4
x5.substring(2,6)
"llen"
x5.slice(2,6)
"llen"
x5.substring(0,-2)
""
x5.slice(0,-2)
"millenni"
x5.slice(2)
"llenni um"

Here we compare the values ​​of slice and substring. When the value range is from a positive number to a negative number, substring cannot take a value. When there is only one parameter of slice, the default value is taken from the current number to the beginning.

Case:

x5.toUpperCase()
"MILLENNI UM"
x6 = x5.toUpperCase()
"MILLENNI UM"
x6.toLowerCase()
"millenni um"

The case conversion here is similar to Python's upper and lower.

2.3.6 Boolean

The Boolean value of JS is different from that of Python. The true and false here are both lowercase , and the empty string, 0, null, undefined, and NaN are all false.

The difference between null and undefined

Null means that the value is empty, which is generally used when a variable needs to be specified or cleared, such as name = nul.

Undefined means that when a variable is declared but not initialized, the default value of the variable is undefined. In addition, when the function has no clear return value, it is also undefined.

2.3.7 Array

The role of the array: use a single variable name to store a series of values, similar to a list in Python.

method

Description

.length

The size of the array

.push(ele)

Append element

.pop()

Get the tail element

.unshift(ele)

Head insert element

.shift()

Remove elements from the head

.slice(start, end)

slice

.reverse()

Reverse

.join(seq)

Concatenate array elements into strings

.concat(val, ...)

Concatenated array

.sort()

Sort

.forEach()

Pass each element of the array to the callback function

.splice()

Delete elements and add new elements to the array.

.map()

Return a new array of the values ​​processed by the array element call function

var a = [2,3,5,[23,54,6,'sod'],6];
undefined
a.push(666)
6
a
(6) [2, 3, 5, Array(4), 6, 666]
var a = [2,3,5,6,[23,54,6,'sod']];
undefined
a.push(12)
6
a
(6) [2, 3, 5, 6, Array(4), 12]
a.pop()
12
a.pop()
(4) [23, 54, 6, "sod"]
a.unshift(666)
5
a
(5) [666, 2, 3, 5, 6]
a.shift();
666
a
(4) [2, 3, 5, 6]
a.slice(1,4)
(3) [3, 5, 6]
a
(4) [2, 3, 5, 6]
a.reverse()
(4) [6, 5, 3, 2]
a.join('?')
"6?5?3?2"
var b = [45,67,89]
undefined
a.concat(b)
(7) [6, 5, 3, 2, 45, 67, 89]
a.sort()
(4) [2, 3, 5, 6]
a.splice(1,2,3)//The first parameter is the start bit, the second parameter is the number of deleted numbers, and the third number is the number added
(2) [3, 5]
a
(3) [2, 3, 6]

forEach()

Syntax: forEach(fuction(currentValue,index,arr),thisValue)

parameter:

parameter

description

currentValue

Current element, must have

index

The index value of the current element, optional

arr

The array to which the current element belongs, optional

thisValue

The object is used when the callback is executed, passed to the function, and used as the value of "this". If thisValue is omitted, the value of "this" is "undefined", and thisValue is the value passed to the defined function (the callback function defined by yourself).

var c = [1,2,3,4,5,6];
c.forEach(function(value){console.log(value)})
VM4997: 2 1
VM4997: 2 2
VM4997: 2 3
VM4997: 2 4
VM4997: 2 5
VM4997: 2 6

For example, the value of the code here is the value of thisValue, and this value is passed to the function we defined.

map()

map(function(currentValue,index,arr), thisValue)

parameter

description

currentValue

Current element, must have

index

The index value of the current element, optional

arr

The array to which the current element belongs, optional

thisValue

The object is used when the callback is executed, passed to the function, and used as the value of "this". If thisValue is omitted, the value of "this" is "undefined", and thisValue is the value passed to the defined function (the callback function defined by yourself).

2.4 Object

In JS, everything is an object such as strings, numbers, arrays, functions..., JS also allows custom objects.

JS also has built-in objects (objects defined in JS that can be used directly) such as String, Date, Array, etc. Objects are just special data types with properties and methods.

2.4.1 Date Object

Create Date object

//Method 1: Do not specify parameters
var d1 = new Date();
console.log(d1.toLocaleString());
//Method 2: The parameter is a date string
var d2 = new Date("2004/3/20 11:12");
console.log(d2.toLocaleString());
var d3 = new Date("04/03/20 11:12");
console.log(d3.toLocaleString());
//Method 3: The parameter is the number of milliseconds
var d3 = new Date(5000);
console.log(d3.toLocaleString());
console.log(d3.toUTCString());

//Method 4: The parameters are year, month, day, hour, minute, second, millisecond
var d4 = new Date(2004,2,20,11,12,0,300);
console.log(d4.toLocaleString());//Milliseconds are not displayed directly

Methods of the Date object

var d = new Date(); 
//getDate() Get the date
//getDay () Get the day of the week
//getMonth () Get the month (0-11)
//getFullYear () Get the full year
//getYear () Get the year
//getHours () Get hours
//getMinutes () Get minutes
//getSeconds () Get seconds
//getMilliseconds () Get milliseconds
//getTime () returns the cumulative number of milliseconds (from 1970/1/1 midnight)

2.4.2 JSON Object

var str1 ='{"gender": "female", "age": 22}';
var obj1 = {"gender": "female", "age": 22};
//Convert JSON strings into objects, which is equivalent to loads in Python
var obj = JSON.parse(str1); 
//The object is converted into a JSON string, which is equivalent to dumps in Python
var str = JSON.stringify(obj1);

2.5 Formatted output

Similar to the formatted output in Python, there are corresponding functions in JS, as follows:

var name ='xiaoyu';
age = 10
10
var res = `my name is ${name}, my age is ${age}.`
undefined
res;
"my name is xiaoyu, my age is 10."
var res = `my name is ${name}, my age is ${age1}.`
VM2935:1 Uncaught ReferenceError: age1 is not defined
    at <anonymous>:1:45
(anonymous) @ VM2935:1
If the variable in the curly braces does not exist, an error will be reported.

2.6 The difference between the two self-additions

var x = 1;
var res1 = x++;//First assign and then add
var res2 = ++x;//Add and then assign
undefined
res1
1
res2
3

2.7 Weak equals (==) and strong equals (===)

Weak equals are automatically converted into the same data type for comparison internally, and strong equals are not converted into data types.

var x1 = 5;
undefined
var x2 = '5';
undefined
x1 == x2;
true
x1 === x2;
false

2.8 Operator

2.8.1 Arithmetic operators

+-*/% ++ -

2.8.2 Comparison operators

> >= <<= != == === !==

2.8.3 Logical operators

&& ||!

2.8.4 Assignment Operator

= += -= *=/=

2.9 Process control

2.9.1 if...else...,if...else if...else...

var x = 20;
if (x> 18){
    console.log('yes');
} else{
    console.log('no');
}

VM187: 3 yes
undefined
var x = 20;
if (x <18){
    console.log('no');
} else if (x <25){
    console.log('hello');
} else{
    console.log('bye')
}
VM192:5 hello

2.9.2switch

Switch is to give multiple conditions, which code is executed whichever condition is met, but a break must be added after each statement, otherwise all the codes below the code will be executed.

var day = new Date().getDay();
switch (day) {
  case 0:
  console.log("Sunday");
  break;
  case 1:
  console.log("Monday");
  break;
default:
  console.log("...")
}
VM416:4 Sunday

2.9.3while

var i = 0;
while (i <3) {
    console.log(i);
    i ++;
}
VM576: 3 0
VM576:3 1
VM576:3 2

2.9.4 Ternary Operation

The ternary operation of js writes the judgment condition first, and then the return value if the condition is satisfied, and the return value if the condition is not satisfied.

var a = 1;
var b = 2;
var c = a> b? a: b;
c
2//The condition is met, return a, if the condition is not met, return b

2.10 How the function is defined

//Ordinary function
function f1 () {
   console.log("Hello world!")
}
//Parameter function
function f2(a,b) {
    console.log(arguments);
    console.log(arguments.length);
    console.log(a,b);
}

//Function with return value
function sum(a,b) {
    return a + b;
}
sum(1,2);//Call function
//Anonymous function method
var sum = function (a,b) {
   return a + b;
}
sum(1,2);
(function (a,b) {
  return a + b;
})(1,2);
//Execute the function immediately. Write the function to be executed immediately. You can write two parentheses ()() to prevent writing confusion

ES6 allows the use of'arrows' (=>) to define functions.

var f = a => a;
//Equivalent to
var f = function (a) {
    return a;
}
//The front of the arrow is the parameter to be passed in, and the back of the arrow is the return value.

If the arrow function does not require parameters or requires multiple parameters, use parentheses to enclose the parameters. If there are no parameters, write only one parenthesis. If there are multiple parameters, use commas to separate them.

var f = () => 5;
//Equivalent to
var f = function () {
    return 5
}

var s = (num1,num2) => num1 + num2
//Equivalent to
var s = function (num1,num2) {
    return num1 + num2;
   /*Unlike python, the return of JS can only return
    One value, if you want to return multiple values, you need to
    Store in an array, and then return the array*/
}

2.10.1 The arguments parameter in the function

arguments[a] represents the a-th formal parameter, the number of arguments.lenth formal parameters.

function f3(a,b) {
    console.log(a+b);
    console.log(arguments.length);//The number of parameters passed in
    console.log(arguments[0]);//Remove the first parameter passed in
}

2.10.2 Function's global variables and local variables

Local variable

In JS, the variables declared inside the function are local variables and can only be used inside the function. The variables will also be deleted when the function runs.

Global variable

The variable declared outside the function is a global variable, which can be used globally and locally.

Variable life cycle

  1. Local variables will be deleted after the function runs
  2. Global variables will be deleted after the page is closed

Scope

First look inside the function. If you can’t find it, go outside the function. Look for it layer by layer. This is very similar to the scope of python.

var x = 1;
function f4() {
    var x = 2;
    function f5() {
        var x = 3;
        console.log(x)
    }
    f5()
}
f4();
3
var y = 1;
function f5() {
    console.log(y);
}

function f6() {
    var y = 2;
    return f5;
}

f6()();
1
var z = 1;
function f7() {
    var z = 2;
    function f8() {
        console.log(z)
    }
    return f8;
}
f7()();
2
Reference: https://cloud.tencent.com/developer/article/1554235 JavaScript-Cloud + Community-Tencent Cloud