〖大前端 - 基础入门三大核心之JS篇(55)〗- 内置对象

2023-12-17 04:55:38
  • 说明:该文属于 大前端全栈架构白宝书专栏目前阶段免费如需要项目实战或者是体系化资源,文末名片加V!
  • 作者:哈哥撩编程,十余年工作经验, 从事过全栈研发、产品经理等工作,目前在公司担任研发部门CTO。
  • 荣誉:2022年度博客之星Top4、2023年度超级个体得主、谷歌与亚马逊开发者大会特约speaker全栈领域优质创作者



? 包装类

很多编程语言都有“包装类”的设计,包装类的目的就是为了让基本类型值可以从它们的构造函数propotype上获得方法

Number()、String()和Boolean()分别是数字、字符串、布尔值的“包装类”

  • new 包装类()得到的变量的类型是对象,是一种特殊的表现形式。比如一个数字123用包装类进行“包装”,就会得到一个被“包装”了的{123},示例代码如下:
var a = new Number(123);
var b = new String('哈士奇');
var c = new Boolean(true);

console.log(a);
console.log(typeof (a));   // object
console.log(b);
console.log(typeof (b));   // object
console.log(c);
console.log(typeof (c));   // object

image-20231108175652253

  • 包装类new出来的虽然是一个对象,但依然可以像普通类型一样可以进行计算、切片或布尔判断等

示例代码:

var a = new Number(123);
var b = new String('哈士奇');
var c = new Boolean(true);

console.log(2 + a);         // 125
console.log(b.slice(0, 2)); // '哈士'
console.log(c && true);     // true

image-20231109095508031

  • 我们定义一个number类型的变量,它的原型就是Number包装类的prototype。也就是说我们定义的number类型的变量可以看作是Number() new出来的。这就是为什么我们基本类型值可以调用一些内置的方法,比如字符串可以直接调用slice()方法、str()方法等

示例代码:

var d = 123;
console.log(d.__proto__ === Number.prototype);   // true,证明变量d是Number new出来的实例

var e = '哈士奇';
console.log(e.__proto__ === String.prototype);   // true,证明变量e是String new出来的实例

console.log(String.prototype.hasOwnProperty('slice'));   // true

// 因为变量e是String() new出来的实例,所有变量e可以调用String.prototype拥有slice方法
console.log(e.slice(0, 2));   

image-20231109100118808

包装类的目的就是为了让基本类型值可以从它们的构造函数prototype上获得方法,这就是js设计包装类的初衷。

注意,包装类是对基本类型值的面向对象封装,像对array这种复杂类型的封装就不能叫做包装类了,undefined和null是没有包装类的

? Math(数学)对象

🌟 Math.round()

Math.round() 可以将一个数字四舍五入为整数

console.log(Math.round(4.56));      // 5
console.log(Math.round(1.49));      // 1
console.log(Math.round(-12.2345));  // -12

image-20231109101627710

  • 利用Math.round()实现四舍五入到小数点后某位:

image-20231109102827474

示例代码:

var a = 1.2672;
console.log(Math.round(a * 100) / 100);   // 1.27

image-20231109103349872

🌟 Math.max()和Math.min()

Math.max() 可以得到参数列表的最大值

Math.min() 可以得到参数列表的最小值

console.log(Math.max(2, 4, 6, 8));   // 8
console.log(Math.min(2, 4, 6, 8));   // 2

image-20231109103757248

  • 利用Math.max()Math.min()得到数组中的最大值和最小值:

    因为Math.max()Math.min()要求参数必须是“罗列”出来,而不能是数组,我们可以利用apply方法(apply方法可以指定函数的上下文,并且以数组的形式传入“零散值”当作函数的参数),将数组以“零散值”的方式传入函数。

    示例代码:

    var arr = [2, 4, 6, 8];
    console.log(Math.max.apply(null, arr));   // 8
    console.log(Math.min.apply(null, arr));   // 2
    
    // 在ES6中,还可以使用“...”运算符来将数组变成零散值传入函数
    console.log(Math.max(...arr));   // 8
    

    image-20231109104957375

🌟 Math.random()

Math.random() 可以得到0~1之间的小数

为了得到[a, b]区间内的整数,可以使用这个公式:paseInt(Math.random() * (b - a + 1)) - a

// 随机数
console.log(Math.random());
console.log(Math.random());
console.log(Math.random());

// 生成[10~20]之间的整数,公式parseInt(Math.random() * (b - a + 1)) + a
console.log(parseInt(Math.random() * 11) + 10);  

image-20231109105929446

? Date(日期)对象

🌟 创建日期对象

使用new Date() 可以得到当前日期,是object类型值


使用new Date(2024, 12, 1)即可得到指定日期的日期对象,注意:第二个参数表示月份,从0开始算,11表示12月;也可以用new Date(‘2024-12-01’)这样的写法

// 获取当前日期对象
var d_now = new Date();
console.log(d_now);           // 当前时间
console.log(typeof d_now);

// 获取指定日期对象
var d1 = new Date(2024, 2, 1);  // 不算时区
var d2 = new Date('2024-06-01'); // 算时区,我们位于东八区,所以是上午8点
console.log(d1);
console.log(d2);

image-20231109133926137

🌟 日期对象的常见方法

日期对象的常见方法:

方法功能
getDate()得到日期1~31
getDay()得到星期0~6
getMonth()得到月份0~11
getFullYear()得到年份
getHours()得到小时数0~23
getMinutes()得到分钟数0~59
getSeconds()得到秒数0~59

示例代码:

var d = new Date();

console.log('日期', d.getDate());
console.log('星期', d.getDay());
console.log('月', d.getMonth());  // 注意因为月份是从0开始算的,如果得到的是10,则表示现在是11月份
console.log('年份', d.getFullYear());
console.log('时', d.getHours());
console.log('分', d.getMinutes());
console.log('秒', d.getSeconds());

image-20231109135225963

🌟 时间戳

时间戳表示1970年1月1日零点整剧离某个时刻的毫秒数


通过getTime()方法(精确到毫秒)或者Date.parse()函数(精确到毫秒)可以将日期对象变为时间戳


通过new Date(时间戳)的写法,可以将时间戳变为日期对象

示例代码:

var d = new Date();

// 显示时间戳的两种方法
var timestamp1 = d.getTime();       // 方法一,精确到毫秒
var timestamp2 = Date.parse(d);       // 方法二,也是毫秒数,但后三位一定是000

console.log(timestamp1);
console.log(timestamp2);

// 把时间戳变回日期对象
var dd = new Date(timestamp1);
console.log(dd);

image-20231109141731171

时间戳的作用: 如果数据库中只存储一个日期对象,是非常麻烦的,如果存储的是一个时间戳(整数)的方式,就会方便很多,也方便进行运算。比如如果需要比较两个时间的大小,直接转换成时间戳,再用比较运算符进行比较就可以了。

🌟 日期对象案例 - 倒计时

**案例:**在页面上显示距离2024年双十一还有多少天、多少小时、多少分、多少秒。

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>距2024年双十一还有:</h1>
    <h2 id="info"></h2>
    <script>
        var info = document.getElementById('info');
        info.style.color = 'red';

        setInterval(() => {
            // 当前时间对象
            var t1 = new Date();
            // 2024年双十一时间对象
            var t2 = new Date('2024-11-11');

            // 计算差值,得到差值的时间戳
            var diff = t2 - t1;

            // 将时间戳转换成天、时、分、秒
            // 包含多少天?diff除以一天的毫秒数再取整,就是天数
            var days = parseInt(diff / (24 * 60 * 60 * 1000));
            // 包含多少小时?diff和一天的毫秒数取余,余数再除以一小时的毫秒数,再取整,就是小时数
            var hours = parseInt(diff % (24 * 60 * 60 * 1000) / (60 * 60 * 1000));
            // 包含多少分?除去天、小时后的余数再除以一分钟的毫秒数,再取整,就是分钟数
            var minutes = parseInt(diff % (24 * 60 * 60 * 1000) % (60 * 60 * 1000) / (60 * 1000));
            // 包含多少秒?出去天、小时、分钟后的余数再除以1000,就是秒数
            var seconds = parseInt(diff % (24 * 60 * 60 * 1000) % (60 * 60 * 1000) % (60 * 1000) / 1000);

            info.innerText = days + '天' + hours + '小时' + minutes + '分钟' + seconds + '秒';
        }, 1000);
    </script>
</body>

</html>

image-20231109145132381

除了上述的方式外,网上还有很多计算两个时间差值的案例,可以尝试通过不同的方式实现这个功能。

文章来源:https://blog.csdn.net/weixin_42250835/article/details/135039983
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。