JavaScript-----13.内置对象 Math()和Date()

1. 内置对象

  • js对象分为3种:自定义对象(var obj={})、内置对象、浏览器对象。
  • 前两种对象是js基础内容,属于ECMAScript,第三个浏览器对象是js独有的。讲js API的时候会讲。
  • 内置对象:js语言自带的一些对象,这些对象供开发者使用,并提供了一些常用的或者最基本而必要的功能(属性和方法),比如求最大值最小值,就不需要自己再去写相关的代码就可用直接利用内置对象得出。程序员将不关心内部是怎么实现的,只要拿出一组数来,就可以直接求出最大值和最小值。
  • 内置对象最大的优点,是帮助我们快速开发。
  • js提供了多个内置对象:Math、Date、Array、String等

2. 查文档

MDN/W3C
MDN官方网址
https://developer.mozilla.org/zh-CN/
如何学习对象中的方法:
step1:查阅该方法的功能
step2:查看里面参数的意义和类型
step3:查看返回值的意义和类型
step4:通过demo进行测试

3. Math对象

3.1 Math.PI、 Math.max()、 Math.min()

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math

//Math数学对象 不是一个构造函数 不需要new一下就可用使用 而是直接用里面的属性和方法即可
console.log(Math.PI); //3.141592653589793  一个属性 圆周率
console.log(Math.max(1, 99, 3)); //9 一个方法 求最大值
//如果给定的参数中至少有一个参数无法被转换成数字,则会返回 NaN。
console.log(Math.max(1, 99, 'pink老师')); //NaN
//如果没有参数,则结果为 - Infinity
console.log(Math.max()); //-Infinity

案例1:利用对象封装自己的数学对象,里面有最大值、最小值、PI

//利用对象封装自己的数学对象,里面有最大值、最小值、PI
var myMath = {
    PI: 3.141592653589793,
    max: function() {
        var maxValue = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            if (arguments[i] > maxValue) {
                var temp = arguments[i];
                arguments[i] = maxValue;
                maxValue = temp;
            }
        }
        return maxValue;
    },
    min: function() {
        var minValue = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            if (arguments[i] < minValue) {
                var temp = arguments[i];
                arguments[i] = minValue;
                minValue = temp;
            }
        }
        return minValue;
    }
};
console.log(myMath.PI);
var a = myMath.max(1, 3, 99, 5);
console.log(a);
var b = myMath.min(1, 3, 99, 5);
console.log(b);

3.2 Math.abs()

console.log(Math.abs(1)); //1
console.log(Math.abs(-1)); //1
console.log(Math.abs('-1')); //1  隐式转换 会把字符串-1转换为数字型
console.log(Math.abs('pink')); //NaN

3.2 Math.floor()

//(1)Math.floor() 向下取整 对于一切数都往最小了的取
console.log(Math.floor(1.1)); //1
console.log(Math.floor(1.5)); //1
console.log(Math.floor(1.9)); //1

console.log(Math.floor(-1.1));//-2
console.log(Math.floor(-1.5));//-2
console.log(Math.floor(-1.9));//-2

3.3 Math.ceil()

//(2)Math.ceil() 向上取整 对于一切数都往最大了的取
console.log(Math.ceil(1.1)); //2
console.log(Math.ceil(1.5)); //2
console.log(Math.ceil(1.9)); //2

console.log(Math.ceil(-1.1)); //-1
console.log(Math.ceil(-1.5)); //-1
console.log(Math.ceil(-1.9)); //-1

3.4 Math.round()

//(3)Math.round() 四舍五入 对于一个数距离取距离起最近的整数,对于.5往大了取
console.log(Math.round(1.1)); //1
console.log(Math.round(1.5)); //2
console.log(Math.round(1.9)); //2

console.log(Math.round(-1.1)); //-1
console.log(Math.round(-1.5)); //-1
console.log(Math.round(-1.9)); //-2

3.5 随机数方法random() 重要

//1.Math对象随机方法 random() 返回一个随机小数x  0<=x<1;
//2.这个方法里面不跟参数
console.log(Math.random());
//4.若想得到两个数之间的随机整数 并且包含这两个数
//Math.floor(Math.random * (max - min + 1)) + min;

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandom(1, 10));
//5.随机点名
var arr = ['apple', 'banana', 'orange', 'pink', 'blue'];
console.log(arr[getRandom(0, 4)]);

案例:猜数字游戏
随机生成一个1~10之间的数,并让用户输入一个数字

  • 如果用户输入的数字大于该数字则继续猜
  • 如果用户输入的数字小于该数字则继续猜
  • 如果用户输入的数字等于该数字则结束程序
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randNum = getRandom(1, 10);
while (true) {
    var num = prompt('请输入一个数字');
    if (num > randNum) {
        alert('输入的数字太大啦,继续猜吧!');
    } else if (num < randNum) {
        alert('输入的数字太小啦,继续猜吧!');
    } else {
        alert('输入正确,程序结束');
        break;
    }
}

作业:要求用户输入1~50之间的一个数字,但是只要10次猜的机会

//要求用户输入1~50之间的一个数字,但是只要10次猜的机会
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randNum = getRandom(1, 50);
for (var i = 10; i > 0; i--) {
    var num = prompt('请输入1~50之间的一个数');
    if (num > randNum) {
        alert('太大啦,继续猜吧!你还有' + (i - 1) + '次机会');
    } else if (num < randNum) {
        alert('太小啦,继续猜吧!你还有' + (i - 1) + '次机会');
    } else {
        alert('答案正确!');
        break;
    }
}

4. 日期对象

4.1日期对象的使用

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date

//回忆
var arr = new Array(); //创建一个数组对象
console.log(arr); //[]
console.log(typeof arr); //object

var obj = new Object(); //创建一个对象实例
console.log(obj); //{}
console.log(typeof obj); //object
//Date() 日期对象 也是一个构造函数 必须用new来创建我们的日期对象
//1. Date()的使用 如果没有提供参数,那么新创建的Date对象表示实例化时刻的日期和时间。
var date = new Date();
console.log(date); //Mon Dec 16 2019 14:38:53 GMT+0800 (中国标准时间)
//2. 常用的写法
//写法1:数字型2019,10,01,或者是字符串型'2019-10-1 8:8:8'
var date1 = new Date(2019, 10, 1);
console.log(date1); //Fri Nov 01 2019 00:00:00 GMT+0800 (中国标准时间)  注意这里返回的是11月不是10月(后面再解释)
var date2 = new Date('2019-10-1 8:8:8');
console.log(date2); //Tue Oct 01 2019 08:08:08 GMT+0800 (中国标准时间)
var date3 = new Date('2019/10/1/8:8:8');
console.log(date3); //Tue Oct 01 2019 08:08:08 GMT+0800 (中国标准时间)

4.2日期格式化

上述方法得到的日期格式对用户不太友好,我们想要2019-8-8 8:8:8格式的日期该怎么办呢?

//格式化日期 年 月 日
var date = new Date();
console.log(date.getFullYear()); //2019 返回当前的年
console.log(date.getMonth()); //11 返回当前的月份 返回的月份比当前的月份少1  因为date.getMonth()获得当月(0-11)
//所以要记得月份加1
console.log(date.getMonth() + 1); //12
console.log(date.getDate()); //16 返回当前的日
console.log(date.getDay()); //1 返回当前星期几  星期天~星期6依次对应0123456
//现在想写一个2019年12月16日星期三
var date = new Date(); //必须先实例化
var year = date.getFullYear();
var month = date.getMonth();
var dates = date.getDate();
var arr = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var day = date.getDay();
console.log('今天是:' + year + '年' + month + '月' + dates + '日 ' + arr[day]); //今天是:2019年11月16日 星期一
var date = new Date();//获取当前的时间所以不要传参数进去
//格式化 时 分 秒
console.log(date.getHours()); //18 得到当前的小时
console.log(date.getMinutes()); //35 得到当前的分钟
console.log(date.getSeconds()); //53 得到当前的秒数
//要求封装一个函数 返回当前的时分秒 格式:时:分:秒
function reTime() {
    var date = new Date();
    //格式化 时 分 秒
    var hour = date.getHours(); //18 得到当前的小时
    hour = hour < 10 ? '0' + hour : hour;

    var min = date.getMinutes(); //35 得到当前的分钟
    min = min < 10 ? '0' + min : min;

    var sec = date.getSeconds(); //53 得到当前的秒数
    sec = sec < 10 ? '0' + sec : sec;

    return hour + ':' + min + ':' + sec;
}
console.log(reTime()); //18:49:07

4.3获取日期总的毫秒数

  • 获取Date总的毫秒数(过去到现在总的毫秒数)
  • Date对象是基于1970年1月1日(世界标准时间)起的毫秒数,经常利用总的毫秒数来计算时间,因为它更精确。
//获得Date总的毫秒数(时间戳)
//1. 通过valueOf()或者getTime()
var date = new Date();
console.log(date.valueOf()); //1576493997344
console.log(date.getTime()); //1576494010514
//2.简单写法(最常用的写法)
var date1 = +new Date(); //+new Date();返回的就是总的毫秒数
console.log(date1); //1576494090710
//3. H5新增,获得总的毫秒数 低版本的浏览器可能不兼容
console.log(Date.now()); //1576494168472
//毫秒数是永远不重复的

4.4案例:倒计时(重点案例)

//倒计时案例
//用时间点a的毫秒数减去时间点b的毫秒数,
//再将其转换为月日年时分秒 转换公式如下
//d天=parseInt(总秒数/60/60/24);
//h小时=parseInt(总秒数/60/60%24);
//m分钟=parseInt(总秒数/60%60);
//s秒=parseInt(总秒数%60);
//注意:1s=1000ms
function countDown(time) {
    var nowTime = +new Date(); //返回当前时间总的毫秒数
    var inputTime = +new Date(time); //返回用户输入时间总的毫秒数
    var times = (inputTime - nowTime) / 1000; //times是剩余时间的总的秒数
    var d = parseInt(times / 60 / 60 / 24);
    d = d < 10 ? '0' + d : d;
    var h = parseInt(times / 60 / 60 % 24);
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60);
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60);
    s = s < 10 ? '0' + s : s;
    return d + '天' + h + '时' + m + '分' + s + '秒';
}
console.log(countDown('2019-12-16 20:30:00')); //00天00时37分42秒
原文地址:https://www.cnblogs.com/deer-cen/p/12047782.html