Knowledge about Date objects

Posted by PHPiSean on Sat, 06 Nov 2021 15:14:54 +0100

Differences between basic data types and complex data types

concept

Basic data type: during storage, the value itself is stored in the variable, so it is also called value type.

Complex data type: during storage, the address (Reference) is stored in the variable, so it is also called reference type.

assignment

The basic data type assigns the stored value to a new variable. After the assignment, the two variables have no relationship. Modifying one of them will not affect the other.

For complex data types, the stored address is assigned to a new variable. After the assignment, the two variables point to the same object. The object is modified through one variable, and the other is also the modified object during access.

compare

Two basic data types are compared to directly compare values.

Two complex data types are compared to compare whether the addresses are the same. In other words, it depends on whether two variables point to the same object.

object

Object: all things are objects. For object-oriented programming languages.

concept

Object in reality: a concrete thing that can be seen and touched. Has properties and behavior. When describing a thing, all nouns are attributes, and all verbs are actions.

Object in js: an abstract concept used to describe specific things. There are also attributes and behaviors. Attributes can be basic data types or complex data types. Behavior: functions.

The object in js is composed of multiple key value pairs.

How objects are declared

1. Pass constructor

var obj = new Object();

2. Literal mode

var obj = {}
//You can also define attributes directly
var obj = {
    name:"zhangsan",
    age:24,
    isMarry:false,
    eat:function(){
        console.log("Dry rice, dry rice, put on the basin");
    }
}

attribute

New attribute

//Format: object. Attribute name = attribute value
obj.height = 175;

modify attribute

//Format: object. Attribute name = attribute value
obj.height = 170;

[note] If yes, it will be modified; if no, it will be added.

Delete attribute

Use delete keyword

//Format: delete object. Attribute name
delete obj.height;

Use properties

1. Dot grammar

//Format object. Attribute name
obj.height

2. Square brackets

//Format object ['property name']
obj['height']

3. Differences

[key] if you access a property that an object does not have, the return value is undefined.

Point syntax cannot use variables. When using variables, the variable name will be accessed as an attribute name.

You can use variables in the way of brackets, and you can also use expressions (string splicing).

Built in object

Math object

Handle js math related functions

//Find the maximum value
var max = Math.max(40, 35, 50, 60);

//Find the minimum value
var min = Math.min(40, 35, 50, 60);

//Find absolute value
var abs = Math.abs(-80);

//rounding
var round = Math.round(1.49999999);

//Round up
var ceil = Math.ceil(1.001);

//Round down and discard decimal places.
var floor = Math.floor(2.9);

//Random number returns a random number between 0 and 1, excluding 1. Including head and not including tail
var random = Math.random();

Random number function

//Find the random integer between n-m
function getRandom(n, m) {
    return Math.floor(Math.random() * (m + 1 - n) + n);
}

Random color case

function getColor(){
    //Defines the variable representing the color, # as a fixed value.
    var str = "#";
    //Defines an array representing hexadecimal. Each element is a number in hexadecimal.
    var arr = ["0","1","2","3","4","5","6",'7',"8","9","A","B","C","D","E","F"];
    //Cycle 6 times to generate random color characters
    for (var i = 0; i < 6; i++) {
        //Gets a random subscript.
        var index = getRandom(0,15);
        str+=arr[index];
    }
    return str;
}

Date object

Processing date

Define Date object

//When creating a date, if you do not specify a specific date, it defaults to the current time.
var d = new Date();
//Specify a specific date
var d = new Date("2021-10-29");
//Numeric form, specifying date
var d = new Date(2021,9,29);

[note] the month obtained in js will be one month smaller than the actual month. Because the month is calculated from 0 in js. The range of months is: 0 ~ 11

method

//Gets the number of milliseconds for the time
d.getTime()
//Set time
d.setTime(86400000);
//Get the number
d.getDate()
//What number is set
d.setDate(10)
//Get month
d.getMonth();
//Set month [note] the month starts from 0. If it exceeds 11, it will be calculated from the second year.
d.setMonth(1)
//Get year
d.getFullYear();
//Set year
d.setFullYear()
//Get day of week
d.getDay()
//Time
d.getHours/d.setHours
//branch
d.getMinutes()/d.setMinutes(20)
//second
d.getSeconds()/d.setSeconds();

Method of displaying date

//Display: Fri Oct 29 2021
d.toDateString() 
///Display hours, minutes and seconds time zone 10:06:06 GMT+0800 (China standard time)
document.write(d.toTimeString())
//Display year, month and day in local format 2021 / 10 / 29
d.toLocaleDateString()
//Display hours, minutes and seconds in local format: 07:00 am
d.toLocaleTimeString()
//Display year, day, hour, minute and second in local format 2021 / 10 / 29 07:00 a.m
d.toLocaleString()

Custom date format

//Format date: mm / DD / yyyy hh:mm:ss
//Parameters: Date object
//Return value: formatted string.
function formatDate(date){
    //Acquisition year
    var year = date.getFullYear();
    //Get month
    var month = date.getMonth();
    //Acquisition day
    var day = date.getDate();

    //When getting
    var h = date.getHours();
    //Get points
    var m = date.getMinutes();
    //Get seconds
    var s = date.getSeconds();
    return `${year}year ${month}month ${day}day ${zeroFill(h)}:${zeroFill(m)}:${zeroFill(s)}`
}

function zeroFill(num){
    return num<10?"0"+num:num;
}

timer

setInterval

Execute the corresponding code according to the cycle. Start a timer.

//fn: function interval executed periodically: how often is it executed? The unit is ms
//Timer ID of the timer.
var timer = setInterval(fn,interval) 

[note] in the position of fn, in addition to the function, you can also write code directly, but the code can only be in the form of string.

clearInterval

Turn off the corresponding timer. The timer ID needs to be turned off.

clearInterval(timer);

Delay device

setTimeout

After delaying for a period of time, execute the specified code and return the unique ID of a delayer.

//fn: function executed periodically. Delay: how long is the delay? The unit is ms
//Timer ID of the timer.
var timer = setTimeout(fn,delay) 

clearTimeout

To close the corresponding delayer, you need an ID of the delayer.

clearTimeout(timer)

Packaging object

Three common wrapper objects: String Number Boolean

Why use wrapper objects?

Wrapper objects can provide us with some properties and methods to facilitate our operation of basic data types.

String object

Create a string object.

var str = new String("Thirty fame, dust and earth, eight thousand miles of clouds and moon");

Methods and properties

//Length of string
str.length

//The character 0~length-1 at the return subscript position is out of range and returns null ''.
var str = b.charAt(15);//Returns the character with subscript 15 to str

//Intercepting string substr (starting subscript, how many characters to intercept)
var str = b.substr(12,3); //Intercept 3 characters from the position with subscript 12. Return to str.

//Intercepted string substring (starting subscript, ending subscript) with header but no tail
var str = b.substring(2,4);//Intercept from the character with subscript 2 to the character with subscript 4, excluding 4

//The truncated string slice (start subscript, end subscript) can write a negative number, which represents the reciprocal
var str = b.slice(2,-1); // Intercept from the character with subscript 2 to the penultimate digit. The last bit is not included.
//Capitalize all English words

a = a.toUpperCase(); 
//Turn lowercase all English words turn lowercase
a = a.toLowerCase();

//Replace (character to replace, character to replace)
var str  = b.replace("thirty","thirteen") //Replace all 'thirty' in the b string with 'thirteen'

//The return value of split string split('separator ') is an array. The array contains the split string. If the delimiter does not exist in the original array, an array containing only the original string is returned.
var res = b.split(","); //Indicates that the string is separated by commas

//Find whether the string contains a character. If so, return the subscript of the character. If not, return - 1;
//If the searched character is multi character, the returned subscript is the subscript of the first character
var res = b.indexOf("dust"); //Find out whether there is a string of 'dust' in the b string. If so, return the subscript of 'dust'.

//Querying whether a string exists in another string returns a Boolean value. true if there is one, false if there is none.
var res = b.incloudes("Dust and soil"); //Find b whether the string contains' dust and earth '.

//The removal of leading and trailing spaces is mainly used in scenarios such as form registration (involving user input).
var res = b.trim();

//Determine whether a string starts with a string.
var res = b.startsWith("thirty") 
console.log(res);

//Judge whether a string ends with a string
var res = b.endsWith("Cloud and moon");
console.log(res);

//Complete the target length of the string from the front: the length that the string will eventually become, and the character used to fill in the character completion.
//Format: str.padstart (target length, 'fill character');
// [note] 1. If the target length is less than the actual length, it is invalid.
//2. If the filling character consists of multiple characters, if it is not enough, it will be filled repeatedly until the target length is filled. If there are still characters left, the following will be discarded.
var num = new String("10");
var res = num.padStart(2,"0");
console.log(res);

Automatic packing

Auto packing: automatically packing basic data types into packing objects.

When the program is executed, if the basic data type uses attributes and methods, js will automatically wrap it as a wrapper object, and then unpack it as the basic data type after execution

//In the following case, you can see that the basic data type can use properties and methods, which shows that the String automatically becomes a String object during execution.
var str = "  Why do you fix the faucet in the wardrobe?"
console.log(str.length);
console.log(str.trim());

Topics: Javascript Front-end