21 day good habit phase i-21

JavaScript Basics

About < script >

< script > can insert Javascript into HTML

There are two ways to use < script >:

  1. Embed Javascript code in web pages

  2. Using an external JavaScript file < script SRC = ". JS" > < / script > usually puts all JavaScript references in the < body > element

  3. Postpone script execution: using the defer attribute, the script will be delayed until the entire page is parsed, and then run the script in the order of occurrence to avoid the situation that the object cannot be found< script defer src = ".js" ></script>

  4. Execute script asynchronously: the < script... / > specified by async attribute will start a new thread and execute the script file imported by the < script... / > element asynchronously. That is, scripts marked async cannot be guaranteed to execute in the order in which they appear


js engine will give priority to parsing var variables and function definitions! After the pre parsing is completed, step by step from top to bottom!
When parsing the var variable, the value will be stored in the "execution environment" instead of assignment. The value is the function of storage!


var keyword: variables defined with var can hold values of any data type. The scope of var declaration is the function scope. Using var to declare a variable anywhere in a function or global is equivalent to declaring it at the top of its interior. This behavior is called Hoisting.


Let keyword: the variables defined by let are consistent with var, and can also save values of any data type. But different from var, let's declaration scope is block scope, that is, it can only act within the block, not outside the scope block. Moreover, let cannot be promoted like var, and the variable cannot be referenced before the let declaration is executed, that is, the "temporary dead zone".

Original value

Raw value: simple data segments stored in the stack, that is, their values are stored directly in the location of variable access.

The original value cannot have attributes. If the original type is initialized with the new keyword, an instance of Object type will be created

Reference value

Reference value: the object stored in the heap, that is, the value stored at the variable is a point er to the memory where the object is stored. Is an instance of a specific reference type

For reference values, you can add, modify, and delete their properties and methods at any time

let person = new Object();
person.name = "Jack";

To determine the type of object, you can use the instanceof operator

console.log(person instanceof Object);//true to judge whether the variable person is object

(reference type and class are not the same concept)

data type

undefined type

Undefined. Variables are declared, but in order to initialize them, the data type defaults to undefined. Do not display. Set the variable value to undefined

NULL type

A null value represents a null object pointer. When a variable needs to save an object, but there is no object to save temporarily, it needs to be filled with null

Boolen type

Boolean type. Literal values are true and false respectively. In some cases, other data types are automatically converted to corresponding Boolean values, such as if control statements

Number type

Number. Can represent integers and floating point numbers.

The precision of floating-point numbers in arithmetic operation is not high. In order to solve the problem that the result of judging 0.1 + 0.2 = = 0.3 is false, it can be replaced by 0.1 + 0.2-0.3 < number.epsilon.

NaN: used to indicate that the operation to return the value failed, such as 0 / 2 calculation. The isNaN() function can judge by parameters and return Boolean values

Numeric conversion:

  1. Number(): the function can convert any data type to a numeric value. For example, the Boolean value true is converted to 1. When converting a string, if the string cannot find the corresponding numeric value, the function will return NaN.
  2. parseInt(): this function is used to convert a string into a numeric value. It is mainly used to judge whether the string contains a numeric pattern. The function will convert from the first non space character. When a non numeric character is encountered or to the end of the string, the function will directly return a numeric value. (parseint can recognize different integer formats. For example, "0xA" will be interpreted as a hexadecimal number. In order to distinguish the numerical format, the function can accept the second parameter to specify the base number. For example, it can recognize a hexadecimal number. The second parameter can be passed in 16.)
  3. parFloat(): since the parseint() function cannot recognize the number after the decimal point of a floating-point number, you can use another function similar to it -- parFloat(). This function recognizes all floating-point formats and ignores zeros at the beginning of the string.

string type

Used to represent a string, identified by double quotation marks or single quotation marks.

1) Once a string is created, the value cannot be changed. To modify the string value in a variable, you must first destroy the original string.

2) toString() converts numeric, Boolean, object, and string values to string types. When performing numerical conversion, you can introduce parameters to the function. For example, toString(2) means that the numerical value is converted into binary form and then into string

3) Template literal: ` keep newline characters

let A = 'first line\nsecond line'//single quotes 
let B = `first line
second line`

4) String interpolation: the template literal supports string interpolation. You can insert one or more values into a continuous definition through ${}

let A = 5;
let B = 4;
let result = `${A} != ${B}`;

5) Template literal label function

Used to customize the behavior of interpolation in template literals

function foo(string,aValue,bValue,sumValue){
  console.log(string); // ["", "+", "=", ""]
  console.log(aValue); // 12
  console.log(bValue); // 5

  return sumValue*2;
let res= foo`${a}+${b}=${a+b}`;
console.log(res) //34

For template literals with n interpolations, the number of expression parameters passed to the label function is n. The first parameter passed to the tag function contains n+1 strings, which is an array composed of all ordinary strings (inserted between expressions), that is ["", "+", "=", ""].

6) Original string

Using String.raw, you can get the original string directly (the original unprocessed version of all strings, such as \ n)

console.log(String.raw`first\nsecond`);//first\nsecond, that is, it will not be converted into the form of escape sequence

symbol type

Symbol is a new raw data type, which represents unique values. Its biggest usage is to define the unique attribute name of an object (there will be no attribute conflict)

Symbols need to be initialized with the Symbol() function. let sym = Symbol();

let a = Symbol();
let b = Symbol();

Through the above example, it can be found that the Symbol() instance is created and used as a new attribute of the object to ensure that it will not overwrite the existing attribute object

To avoid creating a symbol wrapper, the Symbol() function cannot be used as a constructor with the new keyword

let A = new Symbol();// error

Global function registry: if different parts of the runtime need to share and reuse symbols, you can use a string as a key to create and reuse symbols in the global symbol registry, and use the Symbol.for() function

let A = Symbol.for('foo');
let B = Symbol.for('foo');
symbol.keyFor(A);//Query the key "foo" in the global registry

Using symbols as attributes

let s1 = Symbol('foo');
let s2 = Symbol('bar');
let s3 = Symbol('baz');

let o = {[s1]:'fool val'};
console.log(o);//Symbol(foo): "fool val"

//Object.defineProperty directly defines a new property or modifies an existing property on an object and returns the object.
//Object.defineProperty requires three parameters (object, propname and descriptor), namely object, property name and property description
Object.defineProperty(o, s2, {value: 'bar val'});
console.log(o);//Symbol(bar): "bar val"

//Object.defineProperties defines all properties corresponding to the enumerable properties of props on the o object.
Object.defineProperties(o, {
    [s3]: { value: 'baz val' },
    [s4]: { value: 'qux val'}
//Symbol(baz): "baz val"
//Symbol(qux): "qux val"
Object.getOwnPropertyNames(o);//Returns an array of all general attribute names (attributes represented by strings or numeric values) of the specified object itself, such as let o = {baz: 'baz val'};
Object.getOwnPropertySymbols(o);//Returns an array of all Symbol property names of a given object itself.
Object.getOwnPropertyDescriptors(o)//Returns an object that contains both general and symbolic attribute descriptions
Reflect.ownKeys();//Returns an array of two types of property names

Object type

Collection of data and functions

Create an Object type instance: let o = new Object();

Basic reference type

An object is an instance of a specific reference type.

Date type

Create date object

let now = new Date(); The new operator is followed by a constructor, a function used to create a new object.

If no parameter is passed to Date, the created object will save the current Date and time.

Date format

1. Month / day / year: "May 23 / 2021"

2. Month name day, year: "May 23, 2021"

3. Year, month, day: May 23, 2021 (means June 23)

4. May 23, 2021 (International Standard)

1. String parameter Date.parse() for receive date

May 1, 2019: let someDate = new Date(Date.parse("May 23, 2019");

Date.UTC() has the same function as Date.parse(), but is different from Date.parse(). Date.UTC() parameters are year and zero starting month (January is 0).

Transfer may 1, 2019: let somedate = new date (date. UTC (April 1, 2019));

getFullYear()//Use getFullYear() to get the year.
getMounth()//Get month
getDate()//get date
getDay()//Get week
getHours()//Get hours
getMinutes()//Get minutes
getSeconds()//Get seconds

getTime()//getTime() returns the number of milliseconds since January 1, 1970.

setFullYear()//Use setFullYear() to set a specific date.

toUTCString()//Use toUTCString() to convert the date of the current day (according to UTC) to a string.

getDay()//Use getDay() and an array to display weeks, not just numbers.

Display a clock//How to display a clock on a web page.

let now = +new Date(); Returns the number of milliseconds (timestamp)

A countdown tool can be designed using a timestamp

var nowTime = +new Date();//Returns the millisecond timestamp of the current time
var s = parse(nowTime%60);//Calculate seconds
var m = parse(nowTime/60%60);//Calculate minutes
var h = parse(nowTime/3600%24);//Calculate hours
var d = parse(nowTime/3600/24);//Calculation days

RegExp type

A single string is used to describe and match a series of string search patterns that meet a certain syntactic rule. Search patterns can be used for text search and text replacement, such as password complexity analysis.

let expression = /pattern/flags; A regular expression consists of two parts: / regular expression pattern / modifier (optional)

Regular expression pattern

Includes character classes, qualifiers, grouping, forward lookup, and back reference

//1. Character
let a = /ab/i;//Matches the first ab in the string, case insensitive
//2,[abc] 	 Find any characters between square brackets.
let a = /[bc]at/i;//Match the first "bai" or "cat", case insensitive
let b = /[0-9]/i;//Find any number from 0 to 9.
//4. Placeholder
let c = /.at/i;//Find the first three character combination ending at
let a = /ab{2}c/i;//Find the first abbc
let b = /ab{2,}c/i;//Where b appears from 2 to 2
let c = /ab{2, 6}c/i;//b occurs 2 to 6 times

//(x|y) 	 Find any options separated by |
//d 	 Find a number.
//\s 	 Find white space characters.
//\b 	 Match word boundaries.
//\uxxxx 	 Finds Unicode characters specified in hexadecimal number xxxx.
//n+ 	 Matches any string that contains at least one n.
//n* 	 Matches any string containing zero or more n's.
//n? 	 Matches any string containing zero or one n.


iignore - case insensitive
gGlobal - global match (means to find all the contents of the string instead of ending when the first one is found)
mMulti line - multi line match (indicates that the search will continue when the end of a line of text is found)
sIndicates that the metacharacter * *. * * matches any character, including line breaks \ n


The main method exec() of RegExp instance is mainly used with the capture group. Accept a parameter. If a match is found, an array containing the first match information is returned; Otherwise, NULL is returned. The returned array contains two additional properties: index (the starting position of string matching) and input (the string to find)

var a = "a dog";
let b = /a (cat|dog)/i;
let match = b.exec(a);
console.log(match.input);//'a dog'

When the modifier is g, the pattern sets the global flag, and each call to exec() returns the next match of the string until the end of the string is searched. There is a special attribute: lastIndex, which reflects the index of the last character matched


If you just want to test whether the patterns match, you can use the test() method. When a match occurs, it returns true; otherwise, it returns false

Tags: Javascript Front-end

Posted on Thu, 11 Nov 2021 22:57:34 -0500 by pulsedriver