Math对象
1.什么是Math对象?
JavaScript中Math对象是是一个固有对象,提供基本数学函数和常数。使用方法: Math.[{property | method}] 其中property是必选项。Math 对象的一个属性名。 method是必选项。Math.对象的一个方法名。 JavaScript中Math对象不能用 new 运算符创建,如果试图这样做则给出错误。该对象在装载脚本引擎时由该引擎创建。其所有方法和属性在脚本中总是可用。
2.一些常用的无理数的表达方法
console.log(Math.PI); //输出3.1415926535...
console.log(Math.pi=3.1415926535...); //true
console.log(Math.pi==3.14); //false
向上取整
Math.ceil(x)实现向上取整,返回大于等于x且离x最近的整数
1.console.log(Math.ceil(1.1);//输出2
2.console.log(Math.ceil(1);//输出1
3.console.log(Math.ceil(-1.1);//输出-1
向下取整
Math.floor(x)返回小于等于x且离x最近的整数
1.console.log(Math.floor(1.1));//输出1
2.console.log(Math.floor(1));//输出1
3.console.log(Math.floor(-1.1));//输出-2
随机数
Math.random() 返回0到1之间的一个随机数,含0不包含1
1.console.log(Math.random());//输出 :0.1493135392665863
平方根
Math.sqrt(x)返回x的平方根
1.Math.sqrt(4); //2
2.Math.sqrt(2); // 1.4142135623730951
四舍五入
Math.round(x)返回x四舍五入后的整数
1.Math.round(1.5); //2
2.Math.round(1.49); //1
求最值
Math.max(x1,x2,...xn) 返回参数的最大值,参数个数不限;
1.Math.max(1,2,3,4,); //4
2.Math.max(-1,-2,-3); //-1
Math.min(x1,x2,...xn)返回参数的最小值
1.Math.min(1,2,3,4); //1
2.Math.min(-1,-2,-3); //-3
其余方法
Math还有很多的方法,如下表所示:
方法 | 作用 |
Math.abs(x | 求x的绝对值 |
Math.pow(x,y) | 计算x的y次幂 |
Math.exp(x) | e的x次方 |
Math.log(x | x以e为底的对数 |
Math.sin(x) | x的正弦 |
Math.cos(x) | x的余弦 |
Math.tan(x) | x的正切 |
Math.asin(x) | x的反正弦 |
Math.acos(x) | x的反余弦 |
Math.atan(x | x的反正切(-PI/2到PI/2之间) |
Math.atan2(y,x) | x轴到点(x,y)的角度 (-PI/2到PI/2之间) |
日期对象
1.什么是日期对象?
Date是一个内建对象,在JavaScript中使用Date对象来表示一个时间
我们可以用Date() 创建一个Date对象,如果时间使用构造函数创建一个Date对象,则会封装为当前代码执行的时间
var date =new Date(); //创建一个日期对象
console.log(date);//当前时间...
如果我们想要创建一个指定的时间函数,我们则需要在构造函数中传递一个表示时间的字符串作为参数使用
var date2= new Date('2023-03-16 09:23:33');
console.log(date2)//Sun Apr 16 2023 09:23:33 GMT+0800(中国标准时间)
除了这些,我们还可以获取当前的年月日
获取年:
var year=date1.getFullyear();
console.log(year);//浏览器控制台输出2023
获取月:(注意月份需要加1)
var month=date1.getMonth();
console.log(month+1); //浏览器控制台输出:4
获取日
var day=date1.getDate();
console.log(day);//浏览器控制台输出:16
以此类推可以获取小时、分钟、秒等等
2.时间戳
时间戳,指的是从格林威治标准时间的1970年1月1日,0时0分0秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。到当前日期所花费的毫秒数(1秒 =1000毫秒)
我们也可以通过过一个函数获取到当前时间戳:getTime()(获取当前日期对象的时间戳)
获取时间戳的方式有以下几种:
var time1=Date.parse(new Date());
console.log(time1);
var time2=(new Date()).valuesOf();
console.log(time2);
var time3= new Date().getTime();
console.log(time3);
var time4=new Date.now();
console.log(time4);
第一种方法只精确到秒,第二种和第三种和第四种都可以获取当前毫秒的时间戳