python front-end development (JavaScript variables, data types, built-in objects, operators, process controls, functions)

11.4 JavaScript

11.41 variable

1. Grammar of declaring variables

// 1. Declare before define
var name; // There is no need to specify a type or variable when declaring a variable. name Any type is acceptable
name= "egon";
// 2. Declarations are immediately defined
var age = 18;

2. Variable Naming Specification

1. It's composed of letters, numbers, underscores and dollars, but it can't start with numbers, nor can it be pure numbers.
2. Strictly case-sensitive
3. Cannot include keywords and reserved words (keywords to be used in future upgrades).
Such as:
4. Recommended hump nomenclature: When there are several meaningful words to form a name, the first word is lowercase and the rest is initially written.
5. Hungarian Naming: The prefix is the first character of a word of data type.

3. let in ES6

Before ES6, js had no block-level scope. ES6 added let command to declare variables (declared variables belong to block-level scope). The {} of process control statement is block-level scope. Its usage is similar to var, but the declared variables are valid only in the code block where the let command resides. For example, the counter for the loop is well suited to use the let command

for(let i=1;i<=5;i++){
}                       //1 2 3 4 5

4. Constants

ES6 adds const to declare constants. Once declared, its value cannot be changed.

const PI = 3.1415926;
PI=3                    //TypeError: "PI" is read-only

11.42 Data Type

Number 11.421

JavaScript does not distinguish between integer and floating-point types. It has only one numeric type, number.

var x = 3;
var y = 3.1;
var z = 13e5;
var m = 13e-5;
var n = NaN;                    // typeof n Result"number"
var num=1.3456
num.toFixed(2)                  // "1.35"
//Converting string type to number
parseInt("123")                // Return 123
parseInt("ABC")                // Return NaN  NaN Attributes are special values representing non-numeric values,This property is used to indicate that a value is not a number.
console.log(parseInt("18 Jan Lamb")); //18  It has the function of automatic purification; it only keeps the number at the beginning of the string, and the Chinese after it disappears automatically.
console.log(parseInt("Lin Haifeng 18")); // NaN  Only go to the end of the Chinese, not the beginning.
parseInt("123.456")             // Return 123  
parseFloat("123.456")           // Return 123.456    Number Floating Points in Strings
var a = parseInt("1.3") + parseInt("2.6"); //a=3    Automatically with the function of truncating decimals: rounding, not rounding
var a = parseFloat("1.3") + parseFloat("2.6"); //a=3.9
//Converting numeric types to strings
var x=10;
var y='20';
var z=x+y; // z='1020'
typeof z; //String
var m=123;
var n=String(m)//'123'
var a=123;
var b=a.toString()//'123'
11.422 String
var a = "Hello";
var b = "world";
var c = a + b; 
console.log(c);     // obtain Helloworld

Common methods:

Method Explain
.length Return length
.trim() Remove blanks
.trimLeft() Remove the left margin
.trimRight() Remove the right margin
.charAt(n) Returns the nth character
.concat(value, ...) Mosaic, mosaic strings usually use the "+" sign
.indexOf(substring, start) Subsequence position
.substring(from, to) Obtaining subsequences from indexes
.slice(start, end) Section
.toLowerCase() A lowercase letter
.toUpperCase() Capitalization
.split(',', 2) Separate by comma, but show only the first two

The difference between substirng() and silce():

The characteristics of substirng():
If start > stop, start and stop will be exchanged
If the parameter is negative or not a number, it will be replaced by 0.
The characteristics of silce()
If start > stop does not exchange the two
If start is less than 0, the cut begins with the abs(start) character from the end of the string to the front (including the character at that position)
If stop is less than 0, the cut ends with abs(stop) character from the end of the string to the front (excluding the position character)


template string is introduced in ES6: template string is an enhanced version of the string, identified by back quotation marks (`), which is used for

1,It can be used as a normal string.
var msg = `my name is egon`
2,It can also be used to define multi-line strings
var info = `
3,And you can embed variables in strings
var name = "egon";
var age = 18;
var msg = `my name is ${name}, my age is ${age}`;       // "my name is egon, my age is 18"

Be careful:

If backquotes are required in template strings, they are preceded by backslashes

11.423 Boolean Value
var a = true;
var b = false;
//Boolean value false Data type
//Boolean values for the rest of the data types are true

null and undefined:

Null: Null: denotes that the value is empty and is usually used when a variable needs to be specified or cleared, such as name=null; undefined: denotes that when a variable is declared but not initialized, the default value of the variable is undefined. There is also undefined return when the function has no explicit return value. Null means that the value of the variable is empty, undefined means that only the variable is declared, but it has not yet been assigned.

11.43 Built-in Objects

11.431 Array Array

The function of an array object is to store a series of values with a separate variable name. Similar to lists in Python.

var x = ["egon", "hello"];
console.log(x[1]);           // output"hello"

Common methods:

Method Explain
.length Array size
.push(ele) Tail additive element
.pop() Delete tail elements
.unshift(ele) Header insertion element
.shift() Head Removal Element
.slice(start, end) Section
.reverse() Reversal
.join(seq) Connect array elements to strings
.concat(val, ...) Connection array
.sort() sort
.forEach() Pass each element of the array to the callback function
splice(1,2, "new value") Delete elements and add new elements to the array.
.map() Returns a new array of values processed by an array element calling function

Provide a comparison function for sorting. The function should have two parameters a and b, receive incoming A and b, execute function body code, and then return a value to indicate the size of a and B.

Return value < 0: Represents a less than b

Return value = 0: Represents a equals b

Return value > 0: represents a greater than b

function sortNumber(a,b){
    return a - b
var arr = [123,9,1211,11]
arr.sort(sortNumber)                    //[9, 11, 123, 1211]

Traversing through elements in an array:

var arr = [11, 22, 33, 44];
for (var i=0;i<arr.length;i++) {
}                                   //11 22 33 44

forEach() :

Syntax: forEach (function (current element, current element index, array arr to which the current element belongs), thisValue)

var arr=['aa','bb','cc','dd','ee']
//aa 0  ["aa", "bb", "cc", "dd", "ee"] h
//bb 1  ["aa", "bb", "cc", "dd", "ee"] h
//cc 2  ["aa", "bb", "cc", "dd", "ee"] h
//dd 3  ["aa", "bb", "cc", "dd", "ee"] h
//ee 4  ["aa", "bb", "cc", "dd", "ee"] h

splice() :

Syntax: splice

var arr=['aa','bb','cc','dd','ee']
arr.splice(1,3,'xxxx')                  //delete'bb','cc','dd'These three values are then inserted'xxxx'
arr                                   //["aa", "xxxx", "ee"]

map() :

Syntax: map(function (current element, current element index, array arr to which the current element belongs), thisValue)

//String inversion
var str = '12345';, function(x) {             //At the same time, it makes use of it. call()Method
  return x;
}).reverse().join('');                                // "54321"
11.432 Date Date object

There is only one way to create a date object, using the new keyword

//Method 1: No parameters are specified
var d1 = new Date();
console.log(d1.toLocaleString());       //  2020/8/9 8 p.m.:24:06
//Method 2: The parameter is a date string
var d2 = new Date("2018/01/27 11:12:13");
console.log(d2.toLocaleString());       //  2018/1/27 11 a.m.:12:13
var d3 = new Date("01/27/18 11:12:13"); //  month/day/Years, hours and seconds
console.log(d3.toLocaleString());       //  2018/1/27 11 a.m.:12:13
//Method 3: The parameters are milliseconds.
var d4 = new Date(7000);
console.log(d4.toLocaleString());       //  1970/1/1 8 a.m.:00:07
console.log(d4.toUTCString());          //  Thu, 01 Jan 1970 00:00:07 GMT
//Method 4: The parameters are: year, month, day, hour, minute, second, millisecond.
var d5 = new Date(2018,1,27,11,12,13,700);
console.log(d5.toLocaleString());  //Milliseconds are not displayed directly    //  2018/2/27 11:12:13 a.m.

Common methods:

Method Meaning
getDate() Returns the date of the month (1-31) of the specified date object based on local time
getMonth() Returns the month (0-11) of the specified date object based on local time
getFullYear() Returns the year of the specified date object based on the local time (four digits when four digits are returned)
getDay() Returns the day of the week (0-6) of the specified date object based on local time
getHours() Returns the hours of the specified date object based on local time (0-23)
getMinutes() Returns minutes of the specified date object based on local time (0-59)
getSeconds() Returns the number of seconds (0-59) of the specified date object based on local time
getMilliseconds() Returns the acquisition milliseconds of the specified date object based on local time
getTime() Return the cumulative milliseconds (from 1970/1/1 midnight)

Write code to output the current date in the format of "Wednesday 2017-12-27 11:11":

const WEEKMAP = {
    0: "Sunday",
    1: "Monday",
    2: "Tuesday",
    3: "Wednesday",
    4: "Thursday",
    5: "Friday",
    6: "Saturday",
function showTime() {
    var d1 = new Date();
    var year = d1.getFullYear();
    var month = d1.getMonth() + 1;
    var day = d1.getDate();
    var hour = d1.getHours();
    var minute = d1.getMinutes() < 10 ? "0"+d1.getMinutes() :d1.getMinutes();
    var week = WEEKMAP[d1.getDay()];    // 0~6 Weeks
    var dateStr = `
        ${year}-${month}-${day} ${hour}:${minute} ${week}
showTime();                         //   2020-8-9 20:37 Friday
11.433 Math object
Method Meaning
Math.floor() Downward rectification, such as 5.1 to 5
Math.ceil() Upward rectification, such as 5.1 to 6
Math.max(a,b) Finding the Maximum in a and b
Math.min(a,b) Finding the Minimum Values in a and b
Math.random() Random number, default 0-1 random number, if you want to find the number between min and max, the formula is: min+Math.random()*(max-min)
11.434 JSON object
// Object Conversion JSON Character string
var obj2={"name":"egon","age":18};
str2=JSON.stringify(obj2);                //  "{"name":"egon","age":18}"
// JSON Format string to object
var str1='{"name":"egon","age":18}';
var obj1=JSON.parse(str1);
console.log(;                  // 'egon'
console.log(obj1["name"]);               //  'egon'
11.435 RegExp object
1. How to create regular objects 1
//Regular expression of parameter 1
//Parametric 2 matching pattern: common G (global matching; finding all matches instead of stopping after the first match) and I (ignoring case)
var reg1 = new RegExp("^[a-zA-Z][a-zA-Z0-9_]{5,11}$"); //  Matching usernames can only be in English letters, numbers, and_
reg1.test("egon_123") // true            //The initials must be English letters. The shortest length should not be less than 6 bits and the longest should not be more than 12 bits.
Note: Regularize the quotation marks.{}Do not add spaces after commas in

2. How to create regular objects 2
var reg2 = /^[a-zA-Z][a-zA-Z0-9_]{5,11}$/;         // Do not quote
reg2.test("egon_123")                             // true

3. String Four Methods of Combining Object with Regular
var s1="hello world";
s1.match(/l/g)                                 // Regular content["l", "l", "l"]                             // The first index of regular content 0
s1.split(/ /)                                 // ["hello", "world"],Default all cutting
s1.replace(/l/g,'L')                          // "heLLo worLd"

4. Matching pattern g and i
var s2="name:Egon age:18"
s2.replace(/e/,"win")                         // "nam win:Egon age:18"
s2.replace(/e/g,"win")                         // "nam win:Egon ag win:18"
s2.replace(/e/gi,"win")                         //"nam win:win gon ag win:18"

5. Note 1:

1,If regExpObject With global flag g,test()Functions are not searched from the beginning of a string, but from attributes. regExpObject.lastIndex The search begins at the specified index.
2,The default value for this property is 0, so the first time is still to look up from the beginning of the string.
3,When a match is found, test()The function will regExpObject.lastIndex The value is changed to the next index position of the last character of the matching content in the string.
4,When executed again test()When the function is used, the search will begin at the index location to find the next match.
5,So when we use test()If you want to reuse the function after a match test()If the function is searched from scratch, it needs to be manually regExpObject.lastIndex Value reset to 0. 
6,If test()When the function can no longer find matchable text, the function will automatically regExpObject.lastIndex Property reset to 0. 
var reg3 = /egon/g;
reg3.test("egon")    // true,Successful matching
reg3.lastIndex      // Successful matching reg3.lasIndex=4
reg3.test("egon")   // Matching from position 4, this match failed
reg3.lastIndex      // Matching failed. lastIndex Return to 0
reg3.test("egon")   // Successful matching again
6. Note 2:
When we call the RegExpObj.test() method without parameters, it is equivalent to executing RegExpObj.test("undefined"), and / undefined/.test() returns true by default.
var reg4 = /^undefined$/;
reg4.test(); // Returns true
reg4.test(undefined); // Returns true
reg4.test("undefined"); // Returns true

11.44 Operator

//Arithmetic operator:
+ - * / % ++ --
//Comparison operator:
> >=  < <=  !=  ==  ===  !==
//Logical Operator
&& || !
//Assignment Operators
=  +=  -=  *=  /=    

11.45 Process Control

if...else :

var age=18;
if(age > 18){
    console.log('too old');
else if(age == 18){
    console.log('Beautiful girl,Call West');
else {
    console.log('too young');
}                                   // Beautiful girl,Call West

switch :

The case clause in switch usually adds a break statement, otherwise the program will continue to execute the statements in subsequent cases.

var day = new Date().getDay();
switch (day) {
  case 0:
      console.log("Go out on Sunday");
  case 6:
      console.log("Go out on Saturdays");
      console.log("Working day, normal work")
}                                       //Working day, normal work


let i=0;
while (i<=3){

Ternary operations:

var x=1;
var y=2;
var z=x>y?x:y       // 2

11.46 Function

1. Definition and invocation of functions (similar to python)

// Parametric function
function f1() {
  console.log("Hello world!");
// Parametric function
function f2(a, b) {
  console.log(arguments);               // Built-in arguments object
  console.log(a, b);
// Functions with Return Values
function sum(a, b){
  return a + b;
sum(1, 2); 
// Anonymous function
var sum = function(a, b){
  return a + b;
sum(1, 2);
// Immediate execution function
(function(a, b){
  return a + b;
})(1, 2); 

Be careful:

Functions can only return one value, and if multiple values are to be returned, they can only be returned in arrays or objects.

Keywords: PHP JSON less Javascript REST

Added by chetanrakesh on Fri, 16 Aug 2019 17:44:40 +0300