1.内置对象
内置对象是系统预先提供的一些特殊对象,能实现不同的功能。
2.Math
Math是数学对象,跟数学相关的api都在其身上。
下面是一些常用的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 getInt(x){
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
document.onclick = function(){
console.log(getInt(0.5))
};
//返回任意范围的随机整数
function getIntRadom(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():可求得某个底数的幂次方,第一个参数为底数,第二个参数为幂
3.数学弧度与角度
//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 //角度转换成弧度
4.三角函数
Math.sin():返回正弦,参数为弧度值
Math.cos():返回余弦,参数为弧度值
Math.tan():返回正切,参数为弧度值
Math.asin():返回反正弦,参数为弧度值
Math.atan():返回反正切,参数为弧度值
Math.acos():返回反余弦,参数为弧度值
其他API可参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math
5.第三方插件:math.js
①安装
<script src='https://cdn.bootcdn.net/ajax/libs/mathjs/9.3.2/math.min.js'></script>
上面代码放到head标签中即可
该插件方法集成在对象math上,请注意是math而不是Math
大写开头的Math是内置的对象,而小写开头的math是插件
该插件功能较多,建议查看官网:https://mathjs.org/
②方法
以下为几个常用的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)为4开平方根
⑵解决0.1 + 0.2问题
JS中的数字是用IEEE 754 双精度 64 位浮点数来存储的,它由64位组成,这种方式当十进制小数的二进制表示的有限数字超过 52 位时,在 JavaScript 里是不能精确存储的,这时候就存在舍入误差
所以很多采用双精度64位浮点数方式存储数字的语言都是这个结果如:0.1+0.2=0.30000000000000004
此时可以通过使用math.js提供的大数字进行运算解决这种问题
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
原生Math上的方法在math.js上也存在,功能基本一致。
6.日期对象
①创建日期对象
//Date() 当前电脑时间戳
console.log(Date());
let nowT = new Date(); //new一个时间对象,可以接受参数来设置时间戳
console.log(nowT); //返回当前时间
let nowT = new Date(123456789); //这个参数是一个毫秒值 从1970年1月1日00:08: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 nowT = 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); // Wed Jul 28 2021
2.toTimeString():返回的是时:分:秒 时区
let nowT = new Date();
let Time = nowT.toTimeString();
console.log(Time); //20:18:00 GMT+0800 (中国标准时间)
3.toLocaleDateString():返回的是年/月/日
let nowT = new Date();
let Time = nowT.toLocaleDateString();
console.log(Time); // 2021/7/28
4.toLocaleTimeString():返回上午(下午)时:分:秒
let nowT = new Date();
let Time = nowT.toLocaleTimeString();
console.log(Time); // 下午8:21:05
5.toUTCString():返回对应的UTC时间,也就是国际标准时间(比北京晚8个小时)
let nowT = new Date();
let Time = nowT.toUTCString();
console.log(Time); // Wed, 28 Jul 2021 12:23:19 GMT
6.toLocaleString():返回本地时间
let nowT = new Date();
let Time = nowT.toLocaleString();
console.log(Time); // 2021/7/28下午8:24:43
⑤日期方法
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+"";
7.第三方插件:date.js
①安装
date.js是一个用来操作日期的库,官方网站为datejs.com。
下载后插入网页,就可以使用。
<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>
②方法:
date.js在原生的Date对象上面,定义了许多语义化的方法,可以方便地链式使用。
⑴日期信息
Date.today(); // 返回当天日期,时间定在这一天开始的00:00
Date.today().getDayName(); // 今天是星期几
Date.today().is().friday(); // 今天是否为星期五,返回true或者false
Date.today().is().fri(); // 今天是否为星期五,返回true或者false
Date.today().is().november(); // 今天是否为11月,返回true或者false
Date.today().is().nov(); // 今天是否为11月,返回true或者false
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. | 0 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. | 0 to 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. | 0 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 |