JavaScript advanced level 8 (built-in object - Math object and Date object)

1, What are built-in objects

There are three kinds of objects in JavaScript: custom object, built-in object and browser object.
Built in objects refer to some of the built-in objects of JS language. These objects are used by developers and provide some commonly used or most basic and necessary functions (properties and methods). Can help us develop quickly. Including Math, Date, Array, etc.

2, Math object

It is a built-in object, not a constructor, so it does not need new to call. It has properties and methods of mathematical constants and functions. Just use the properties and methods inside directly. Math related operations (absolute value, rounding, maximum value, etc.) can use members in math.

1. PI

Math.PI

console.log(Math.PI);
//output
3.141592653589793

2. Absolute value

Math.abs(x)

console.log(Math.abs(-1))//Absolute value, the result is 1
console.log(Math.abs('-1'));//The result is 1. Implicit conversion will convert string type - 1 to number type
console.log(Math.abs('Zhang San'));//The result is NaN

3. Returns the y power of x

Math.pow(x,y)

console.log(Math.pow(2,2));//The result is 4

4. Returns the arithmetic square root of x

Math.sqrt(x)

console.log(Math.sqrt(4));//The result is 2
console.log(Math.sqrt(9));//The result is 3

5. Returns a random number

Math.random(), which returns a random decimal with a range of [0,1], is not followed by a parameter in this method

console.log(Math.random());//The result is 0.01669892240751062

(1) Case 1

Get a random integer between two numbers and include the two integers

function getRandom(min,max){
    return Math.floor(Math.random()*(max-min+1))+min;
}
console.log(getRandom(1,10));

(2) Case 2

Random roll call

//Random roll call
function getRandom(min,max){
    return Math.floor(Math.random() * (max-min+1)) + min;
}
var student = ['Zhang San','Li Si','Wang Wu','Zhao Liu'];

console.log(student[getRandom(0,(student.length-1))]);

(3) Case 3

Figure guessing game

// The program randomly generates a number between 1 and 100, and allows the user to enter a number
// 1. If it is greater than this number, you will be prompted that the number is large and continue to guess
// 2. If it is less than this number, you will be prompted that the number is small and continue to guess
// 3. If it is equal to this number, you will be prompted to guess correctly and end the program
function getRandom(min,max){
    return Math.floor(Math.random() * (max-min+1)) + min;
}
var random = getRandom(1,100);
while(true){
    var x = prompt("Please enter a number and see if you can guess it correctly");
    if(x > random){
        alert("The number is big. Keep guessing");
    }else if(x < random){
        alert("The number is small. Keep guessing");
    }else{
        alert("You guessed right");
        break;
    }
}

(4) Case 4

Guess number game upgrade

//Users are required to guess a number between 1 and 50, but they have only 10 chances to guess
function getRandom(min,max){
    return Math.floor(Math.random() * (max-min+1)) + min;
}
var random = getRandom(1,50);
for(var i = 1;i < 11;i++){
    var x = prompt("Please enter a number and see if you can guess it correctly");
    if(x > random){
        alert("The number is big. Keep guessing");
    }else if(x < random){
        alert("The number is small. Keep guessing");
    }else{
        alert("You guessed right");
        break;
    }
}

6. Rounding

(1)Math.floor(x)

Round down, take the minimum value, and return the maximum integer less than or equal to x.

console.log(Math.floor(1.8));//The result is 1

(2)Math.ceil(x)

Round up, round up to the maximum, and the function returns the smallest integer greater than or equal to x.

console.log(Math.ceil(1.1));//The result is 2

(3)Math.round(x)

Rounding

console.log(Math.round(1.3));//The result is 1, rounded
console.log(Math.round(-1.1));//The result is - 1
console.log(Math.round(-1.5));//The result is - 1, and other numbers are rounded, but. 5 is special. It takes the larger, so when it is negative, it takes - 1

7. Maximum and minimum

(1) Maximum

Math.max(): returns the maximum value in the parameter

console.log(Math.max(1,99,3));//Find the maximum value and 99 will be output
console.log(Math.max(1,'Zhang San'));//If there is a non numeric type, NaN will be returned
console.log(Math.max());//If nothing is written, it outputs - Infinity

(2) Minimum value

Math.min(): returns the minimum value in the parameter

console.log(Math.min(1,99,3));//Finding the minimum value will output 1
console.log(Math.min(1,'Zhang San'));//If there is a non numeric type, NaN will be returned
console.log(Math.min());//If nothing is written, it outputs - Infinity

case

Encapsulate their own mathematical objects, which have PI maximum and minimum values

var myMath = {
    PI: 3.1415926,
    max:function(){
       var max = arguments[0];
       for (var i = 1;i < arguments.length;i++){
           if(arguments[i] > max){
              max = arguments[i];
        }
      }
      return max;
    },
    min:function(){
       var min = arguments[0];
       for (var i = 1;i < arguments.length;i++){
           if(arguments[i] < min){
               min = arguments[i];
            }
       }
       return min;
    },
}
console.log(myMath.PI);
console.log(myMath.max(1,2,3));
console.log(myMath.min(1,2,3));
//The result is
3.1415926
3
1

3, Date object

1. Construction method

Date() is a constructor. To get the current time, we must instantiate it, that is, we must use new to call to create our date object.

(1) Nonparametric structure

If there are no parameters, the current time of the current system is returned

var date = new Date();
console.log(date);
//The result is:
2021-12-02T07:28:25.983Z//The time will be eight hours less than the current time, which is due to different time zones

(2) Parametric structure

If there is a parameter in parentheses, the time in the parameter is returned. The specific form is as follows:

Numeric type: new Date(y,M,d,h,m,s): a structure with parameters. The parameters are year, month, day, hour, minute and second
String type: new Date(dateString): the parameter is a date string

Note: the integer value of the month, from 0 (January) to 11 (December)

var date1 = new Date(2021,12,2,15,33,33);
console.log(date1);//Enter December, and the returned month is one more month
var date2 = new Date('2021-12-2 12:12:12');
console.log(date2);
//Output is:
2022-01-02T07:33:33.000Z//The output month is one more month, and the time is eight hours less than the current time
2021-12-02T04:12:12.000Z//The month is correct, but the time is still eight hours less than the current time

2. Date formatting

When you need to get the part specified by the date, use the following method:

A. getFullYear(): get 4-digit year
B. getMonth(): get the month between 0 and 11
C. getDate(): get the date (the day of the month)
D. getDay(): get the day of the week (the day of the week), 0 is the day of the week
E. getHours(): get hours
F. getMinutes(): get minutes
G. getSeconds(): get seconds
H. getMilliseconds(): returns the number of milliseconds of the specified date object

//format date
var date = new Date();
console.log(date.getFullYear());//Returns the year of the current date
console.log(date.getMonth());//Returns the current month (0-11), so it will be one month smaller
console.log(date.getDate());//What number to return
console.log(date.getDay());//Return to the day of the week, its Sunday is 0, and others are normal
//Format date hour minute second
var date = new Date();
console.log(date.getHours());//Time
console.log(date.getMinutes());//branch
console.log(date.getSeconds());//second
console.log(date.getMilliseconds());//millisecond
//Output is:
2021
11
2
4
15
52
41
525

Example: we write a Thursday, December 2, 2021

//Let's write a Thursday, December 2, 2021
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var day = date.getDay();
var arr = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

console.log("Today is:"+year+"year"+month+"month"+dates+"day "+arr[day]);//Because the day output is the week index, which is not in line with our habit of getting the day of the week, we adopt the array method
//Output is:
Today is Thursday, December 2, 2021

For example, it is required to encapsulate a function to return the current time, minute and second format 00:00:00

//It is required to encapsulate a function to return the current time, minute and second format 08:08:08
function getTime(){
    var time = new Date();
    var h = time.getHours();
    h = h < 10 ? '0'+ h : h;
    var m = time.getMinutes();
    m = m < 10 ? '0'+ m : m;
    var s = time.getSeconds();
    s = s < 10 ? '0'+ s : s;
    return h + ':' + m + ':' + s
}
console.log(getTime());
//Output is:
16:25:35

3. Gets the total number of milliseconds of the date

The Date object is based on the number of milliseconds from January 1, 1970 (world standard time). We often use the total number of milliseconds to calculate the time because it is more accurate.

valueOf()
getTime()
+new Date()
Date.now()

//The total number of milliseconds (timestamp) obtained from Date is not the number of milliseconds of the current time, but the number of milliseconds since January 1, 1970
//1. Gettime() via valueof()
var date = new Date();
console.log(date.valueOf());//The total number of milliseconds from January 1, 1970
console.log(date.getTime());
//2. Simple writing (the most commonly used writing)
var date1 = +new Date();
console.log(date1);
//3. H5 total number of milliseconds newly obtained (the old version may not be applicable)
console.log(Date.now());
//Output is:
1638433853305
1638433853305
1638433853312
1638433853312

4. Conversion format

toDateString(): converts a date to a character
toLocaleDateString(): converts a date to a string in local date format

var date = new Date();
console.log(date.toDateString());
console.log(date.toLocaleDateString());
//Output is:
Thu Dec 02 2021
2021-12-2

5. Case 1 (countdown)

How many days do we have before January 1, 2022
Core algorithm: the input time minus the current time is the remaining time, which is done with a timestamp. The total number of milliseconds of the user input time minus the number of milliseconds of the current time is the number of milliseconds of the remaining time, and then the total number of milliseconds of the remaining time is converted into days, hours, minutes and seconds.

//count down
//Core algorithm: the remaining time is the input time minus the current time. It is done with a timestamp. The total time entered by the user
//The number of milliseconds minus the number of milliseconds in the current time is the number of milliseconds in the remaining time, and then convert the total number of milliseconds in the remaining time into days, hours, minutes and seconds
function countDown(time){
    var nowTime = +new Date();//Returns the total number of milliseconds of the current time
    var inputTime = +new Date(time);//Returns the total number of milliseconds of user input time
    var times = (inputTime - nowTime) / 1000;
    var d = parseInt(times / 60 / 60 / 24);//day
    d = d < 10 ? '0' + d : d;
    var h = parseInt(times / 60 / 60 % 24);//Time
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60);//branch
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60);//second
    s = s < 10 ? '0' + s : s;
    return d + 'day' + h + 'Time' + m + 'branch' + s + 'second';
}
console.log('You still have to wait until January 1, 2022 '+countDown('2022-1-1 00:00:00'));
//Output is:
You have 29 days to go before January 1, 2022 at 04:09:18

6. Case 2 (fishing in three days and drying the net in two days)

Assuming that 2008-08-08 is the first day to dry the net, is today "fishing" or "drying the net".

//"Fishing in three days and drying the net in two days". Assuming that it was "drying the net" on August 8, 2008, is it "fishing" or "drying the net" today 
function fish(){
    var nowTime = +new Date();
    var upTime = +new Date('2008-8-8');
    var time = (nowTime - upTime)/1000;
    var n = parseInt(time/60/60/24)%5;
    var arr = ['Drying net','Drying net','fish','fish','fish'];
    var thing = arr[n];
    console.log(thing);
}
fish();
//Output is:
fish

Tags: Javascript Front-end

Posted on Fri, 03 Dec 2021 10:10:51 -0500 by blues