boxmoe_header_banner_img

Hello! 欢迎来到盒子萌!

加载中

文章导读

11内置对象


avatar
Jack 2022年 11月 11日 75

内置对象是系统预先提供的一些特殊对象,能实现不同的功能

Math

Math是数学对象,跟数学相关的api都在其身上

下面来了解些常用对象

  • Math.random() 随机生成0到1之间的数 包括0不包括1

    document.onclick = ()=>{
      console.log(Math.random())
    }
    
    //生成任意范围的随机数
    let getRandom = (min,max)=> Math.random()*(max-min)+min
    document.onclick =()=>{
      let x = getRandom(5,10)
      console.log(x)
    }
  • Math.ceil() 向上取整(天花板值) 遇到小数向上取整

    console.log(Math.ceil(1.1)) //2
  • Math.floor() 向下取整(地板值) 遇到小数向下取整

    console.log(Math.floor(1.9)) //1
    
    //返回任意范围的随机整数
    function getIntRandom(min,max){
      return Math.floor(Math.random()*(max-min)+min)
    }
    console.log(getIntRandom(2,6))
  • Math.round() 四舍五入

  • Math.max() 取得最大值

  • Math.min() 取得最小值

    //随机排序
    let arr = [2,4,8,7,1,6,9]
    document.onclick = function(){
      arr.sort(function(){
        return Math.random()-0.5
    })
    console.log(arr)
    }
  • Math.pow() 指数 第一个参数为底数 第二个参数为幂

数学弧度与角度

//60° = π/3
//90° = π/2  角度转弧度

//弧度 = 角度 * π/180
//求一个半径为5的圆心面积
let x = 5
let y = Math.PI*Math.pow(x,2) // 圆心面积算法
注意:JS三角函数里面的参数值不是角度 是角度对应的弧度值

//30度角对应的弧度制
let angle = 30
let randian = angle*Math.PI/180  //角度转换成弧度

三角函数

  • Math.sin() 返回正弦 参数为弧度值
  • Math.cos() 返回余弦
  • Math.tan() 返回正切
  • Math.asin() 返回反正弦
  • Math.atan() 返回反正切
  • Math.acos() 返回反余弦

其他API可参考MDN(opens new window)

第三方插件:mathjs

安装

<script src='https://cdn.bootcdn.net/ajax/libs/mathjs/9.3.2/math.min.js'></script>

上面代码放到head标签中即可

该插件方法集成在对象math上,请注意math不是Math

大写Math是内置的,math是插件

该插件功能较多,建议查看官网:mathjs(opens new window)

方法

这里主要讲几个常用的api

计算表达式结果

math.evaluate('1 + 2 * 3') // 7
math.evaluate('(1 + 2) * 3') // 9
math.evaluate('1 + 2^2') // 5
math.evaluate('1 - sqrt(4)') // -1            sqrt(4)开平方根

解决0.1+0.2问题

JS中的数字是用IEEE 754 双精度 64 位浮点数 (opens new window)来存储的,它由64位组成,这种方式当十进制小数的二进制表示的有限数字超过 52 位时,在 JavaScript 里是不能精确存储的,这时候就存在舍入误差

所以很多采用双精度64位浮点数方式存储数字的语言都是这个结果0.1+0.2=0.30000000000000004

此时可以用mathjs提供的大数字进行运算,就能解决这种问题

math.config({
  number: 'BigNumber',
  precision: 64
});
+math.evaluate('0.1+0.2').toString() // 0.3字符串 需要的话 可以前面 + 转成 数值    
//此时evaluate返回是一个对象,想要得到能理解的结果,调用toString方法即可

随机数

正常来说,原生Math.random只能随机0到1之间的数字,用起来很不方便

math.random(min, max)可随机指定区间的任意数字,min指定最小边界,max最大边界,区间为左闭又开

math.random(1, 5) // 随机1到5区间任意数字

math.randomInt(min, max),可随机指定区间的任意整数,min指定最小边界,max最大边界,区间为左闭又开

math.randomInt(1, 5) // 随机1到5之间任意整数

四舍五入

math.round(浮点数,保留位数)保留小数位四舍五入

// 保留三位小数
math.round(3.1415926, 3) // 3.142  

日期对象

创建日期对象

//Date() 当前电脑时间戳
console.log(Date())
let nowT = new Date() //new一个时间对象,可以接受参数来设置时间戳
console.log(nowT) //返回当前时间
let nowT = new Date(123456789) //这个参数是一个毫秒值 从1970年1月1日00:00:00开始加上这个一个毫秒值
let nowT = new Date("January 6,2014") //参数为日期字符串
let nowT = new Date(2019,5,1,19,30,50,20) //参数为多个整数包括:年 月 日 时 分 秒 毫秒  注意:这里的月份是从0开始的
let nowT = new Date("2019-5-1")
let nowT = new Date("2019/5/1")
//注意:字符串参数是时间节点 数字参数会默认为毫秒值

日期对象运算

let nowT1 = new Date(2019,5,1)
let nowT2 = new Date()
console.log(nowT1 - nowT2) //得到的是一个毫秒值
console.log(nowT1 + nowT2) //字符串的拼接

日期对象的静态方法

let nowT = Date.now() //返回当前事件距离1970年1月1日00:00:00之间的时间戳距离
let nowT = Date.parse(2019,5,1) //接收一个日期字符串 返回从1970-1-1 00:00:00到该日期的毫秒数
let noeT = Date.UTC(2019,5,1) //接收以逗号隔开的日期参数 返回从1970-1-1 00:00:00到该日期的毫秒数 接收的月份是0-11

日期格式化方法

  1. toDateString() 返回的是星期 月 日 年

    let nowT = new Date()
    let Time = nowT.toDateString()
    console.log(Time)
  2. toTimeString() 返回的是时 分 秒 时区

    let nowT = new Date()
    let Time = nowT.toTimeString()
    console.log(Time)
  3. toLocaleDateString() 返回的是年 月 日

    let nowT = new Date()
    let Time = nowT.toLocaleDateString()
    console.log(Time)
  4. toLocaleTimeString() 返回本地时 分 秒

    let nowT = new Date()
    let Time = nowT.toLocaleTimeString()
    console.log(Time)
  5. toUTCString() 返回对应的UTC时间 也就是国际标准时间 比北京晚8个小时

    let nowT = new Date()
    let Time = nowT.toUTCString()
    console.log(Time)
  6. toLocaleString() 返回本地时间

    let nowT = new Date()
    let Time = nowT.toLocaleString()
    console.log(Time)

日期方法

  1. getTime() 返回一个毫秒值 到时间零点的距离
  2. getFullYear() 返回年
  3. getMonth() 返回月 注意:得到的月份是从0开始 要返回当前月需要加1
  4. getDate() 返回日期
  5. getHours() 返回小时
  6. getMinutes() 返回分钟
  7. getSeconds() 返回秒
  8. getDay() 返回星期
  9. getTimezoneOffset() 返回是当前事件与UTC的时区差异 以分钟数表示(考虑夏令营时)

获取当前时间

let nowT = setInterval(()=>{
    let oWrap = document.getElementById("wrap")
    let date = new Date(),
        oYear = date.getFullYear(),
        oMonth = date.getMonth(),
        oDate = date.getDate(),
        oHours = date.getHours(),
        oMinut = date.getMinutes(),
        oSecond = date.getSeconds(),
        oDay = date.getDay(),
        aDayArr = ["日","一","二","三","四","五","六"];
    oWrap.innerHTML = `现在的时间是${oYear}年${oMonth}月${oDate}日,星期${aDayArr[oDay]},${oHours}时${oMinut}分${oSecond}秒`
},1000)

let add0 = n => n=n<10?"0"+n:n+""

第三方插件:date.js

安装

Datejs是一个用来操作日期的库,官方网站为datejs.com (opens new window)

下载后插入网页,就可以使用。

<script src="https://cdn.bootcdn.net/ajax/libs/datejs/1.0/date.min.js"></script>

官方还提供多种语言的版本,可以选择使用。

// 美国版
<script type="text/javascript" src="date-en-US.js"></script>

// 中国版
<script type="text/javascript" src="date-zh-CN.js"></script>

方法

Datejs在原生的Date对象上面,定义了许多语义化的方法,可以方便地链式使用。

日期信息

Date.today() // 返回当天日期,时间定在这一天开始的00:00 
Date.today().getDayName() // 今天是星期几
Date.today().is().friday()      // 今天是否为星期五,返回true或者false
Date.today().is().fri()         // 等同于上一行
Date.today().is().november()    // 今天是否为11月,返回true或者false
Date.today().is().nov()         // 等同于上一行
Date.today().isWeekday() // 今天是否为工作日(周一到周五)

日期的变更

Date.today().next().friday()    // 下一个星期五
Date.today().last().monday()    // 上一个星期一
new Date().next().march()       // 下个三月份的今天
new Date().last().week()        // 上星期的今天
Date.today().add(5).days() // 五天后
Date.friday() // 本周的星期五
Date.march() // 今年的三月
Date.january().first().monday() // 今年一月的第一个星期一
Date.dec().final().fri() // 今年12月的最后一个星期五
// 先将日期定在本月15日的下午4点30分,然后向后推90天
Date.today().set({ day: 15, hour: 16, minute: 30 }).add({ days: 90 })
(3).days().fromNow() // 三天后
(6).months().ago() // 6个月前
(12).weeks().fromNow() // 12个星期后
(30).days().after(Date.today()) // 30天后

日期的解析

Date.parse('today')
Date.parse('tomorrow')
Date.parse('July 8')
Date.parse('July 8th, 2007')
Date.parse('July 8th, 2007, 10:30 PM')
Date.parse('07.15.2007')

获取想要的格式

// 想要拿到当前时间的格式:2021-05-22 17:00:00
new Date().toString('yyyy-MM-dd HH:mm:ss')

参数写法参考

Format Description Example
s The seconds of the minute between 0-59. to 59
ss The seconds of the minute with leading zero if required. 00 to 59
m The minute of the hour between 0-59. or 59
mm The minute of the hour with leading zero if required. 00 to 59
h The hour of the day between 1-12. 1 to 12
hh The hour of the day with leading zero if required. 01 to 12
H The hour of the day between 0-23. to 23
HH The hour of the day with leading zero if required. 00 to 23
d The day of the month between 1 and 31. 1 to 31
dd The day of the month with leading zero if required. 01 to 31
ddd Abbreviated day name. Date.CultureInfo.abbreviatedDayNames. Mon to Sun
dddd The full day name. Date.CultureInfo.dayNames. Monday to Sunday
M The month of the year between 1-12. 1 to 12
MM The month of the year with leading zero if required. 01 to 12
MMM Abbreviated month name. Date.CultureInfo.abbreviatedMonthNames. Jan to Dec
MMMM The full month name. Date.CultureInfo.monthNames. January to December
yy Displays the year as a two-digit number. 99 or 07
yyyy Displays the full four digit year. 1999 or 2007
t Displays the first character of the A.M./P.M. designator. Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator A or P
tt Displays the A.M./P.M. designator. Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator AM or PM
S The ordinal suffix of the current day. st, nd, rd, or th


评论(0)

查看评论列表

暂无评论


发表评论

表情 颜文字
插入代码