Date对象
表示一个时间
- 如果直接使用构造函数创建一个Data对象,则会封装当前代码执行的时间
var d = new data();
- 创建一个指定的时间对象(传递一个表示事件的字符串作为参数)
格式:月/日/年 时:分:秒
var d2 = new Date("3/31/2018 16:30:30");
getDate()
获取当前日期对象是几日
var date = d.getDate();
getDay()
获取当前日期对象是周几(0-6:0表示周日)
var day = d.getDay();
getMonth()
获取当前日期对象的月份(0-11:0表示一月)
var mon = d.getMonth();
getFullYear()
获得当前日期对象的年份
var year = d.getFullYear();
getTime()
获取当前日期对象的时间戳
时间戳,指的是从格林威治标准时间的1970年1月1日,0时0分0秒到当前日期所花费的毫秒数(1秒 = 1000毫秒)
计算机底层在保存时间时使用都是时间戳
var time = d.getTime();
Date.now()
获取当前的时间戳
var time = Data.now();
可以用它来测试代码执行的性能,分别在代码前后使用,相减得出执行所用时间
var start = Date.now();
for(var i=0 ; i<100 ; i++){
console.log(i);
}
var end = Date.now();
console.log("执行了:"+(end - start)+"毫秒");
Math对象
Math和其他的对象不同,它不是一个构造函数,它属于一个工具类不用创建对象,它里边封装了数学运算相关的属性和方法
比如:
Math.PI
表示的圆周率
console.log(Math.PI);//3.141592653589793
abs()
可以用来计算一个数的绝对值
console.log(Math.abs(-1));//1
Math.ceil()
可以对一个数进行向上取整,小数位只有有值就自动进1
console.log(Math.ceil(1.1));//2
Math.floor()
可以对一个数进行向下取整,小数部分会被舍掉
console.log(Math.floor(1.99));//1
Math.round()
可以对一个数进行四舍五入取整
console.log(Math.round(1.4));//1
Math.random()
可以用来生成一个0-1之间的随机数
生成一个0-x之间的随机数
Math.round(Math.random()*x)
生成一个x-y之间的随机数
Math.round(Math.random()*(y-x)+x)
for(var i=0 ; i<100 ; i++){
//生成0-10之间的数
console.log(Math.round(Math.random()*10));
//生成0-20之间的数
//console.log(Math.round(Math.random()*20));
//生成1-10之间的数
//console.log(Math.round(Math.random()*9)+1);
//生成2-10之间的数
//console.log(Math.round(Math.random()*8)+2);
//生成1-6之间的随机数
//console.log(Math.round(Math.random()*5+1));
}
max()
可以获取多个数中的最大值
var max = Math.min(10,45,30,100);
console.log(max);//100
min()
可以获取多个数中的最小值
var min = Math.max(10,45,30,100);
console.log(min);//10
Math.pow(x,y)
返回x的y次幂
console.log(Math.pow(12,3));//1728
Math.sqrt()
用于对一个数进行开方运算
console.log(Math.sqrt(2));//1.4142135623730951