数学处理
math常用api
math.pi=3.14
生成随机数
math.random()
生成的是0-1之间随机的小数,通常在项目之中需要获取到一个范围内的整数,利用随机数封装一个获取范围内随机整数的函数
function getrandom(){
var max=a
var min=b
if(a<b){
max=b
min=a
}
var num=parseInt(math.ceil()*(max-min)+min)
return num
}
向上取整
向上取整的含义就是一个数字的小数部分不够1,将他处理为1
math。ceil(3.3)////4
向下取整
向下取整跟parseInt()是一个意思,只要整数部分,舍掉小数部分
math.ceil(3.9)///3
四舍五入
math.round(3.3) ///3
math.round(3.9) ///4
求次方
math.pow()
求平方根
math.sqrt()
绝对值
math.abs()
math.abs()
最大值
math.max()
最小值
math.min()
正弦
math.sin(math.pi*30/180)
余弦
math.cos(math.pi*60/180)
进制转换
10进制转换为其他进制:10进制数字.tostring()
x.tostring
其他进制转换为10进制:parseInt()
parseInt()
时间日期处理
js提供了一个构造函数date,用来创建时间日期对象,所以跟时间日期有关的操作都是通过时间日期处理对象来操作的
时间日期对象创建
当前时间的时间日期对象
var date=new date()
创建好的是一个对象,但是当输出的时候被浏览器自动转为字符串输出了。获取到的是当前本地的时间日期对象。如果把本地的时间日期改掉,获取到的时间日期对象会随着本地时间变化。
指定时间日期对象
var date=new date(指定的时间)
var time=new getTime()
获取具体的时间日期
通过时间日期对象可以获取到具体的时年月日时分秒,甚至毫秒和时间戳
date.getFullYear();
date.getMonth();
date.getDate();
date.getDay();
date.getHours();
date.getMinutes();
date.getSeconds();
date.getMilliseconds();
date.getTime();
时间戳指的是格林尼治时间1970年1月1日0点0分0秒到现在走过的毫秒数,利用时间戳可以方便计算
设置时间日期
通过时间日期对象,可以将其中的年月日时分秒进行设置,改变时间日期对象的时间
date.setFullYear(年份);
date.setMonth(当前月份-1);
date.setDate(日);
date.setHours(时);
date.setMinutes(分);
date.setSeconds(秒);
date.setMilliseconds(毫秒);
date.setTime(时间戳);
特殊,星期不是自己设置的而是生成的,所以星期是不能设置的
日期格式化
date.toLocalString();
date.toLocaleDateString();
date.toLocaleTimeString();
时间戳的获取
格林尼治
date.parse(2023-08-12)
new date().getTime()
+new date()