JS内置函数和对象:
js中内置了一些函数和对象,直接可以调用开发。
根据ECMAscript提供的内置函数包括Object、Array、Boolean、Number、String、Function、Date、Regexp和Error。内置对象包括Math和JSON。
一、Date 日期对象
1. 定义日期对象
var time=new Date();
2. 设置时间
// 1. 不设置,则为当前时间
var times=new Date();
// 2. 用数字赋值
var times=new Date(year, month, day, hours, minutes, seconds, milliseconds)
var times=new Date(2019,2,4,12,43,38,39);
console.log(times);
//Mon Mar 04 2019 12:43:38 GMT+0800 , JS从0到11计算月份。一月是0,十二月是11。
//从0-6计算星期,0是星期天,1-6是星期一到星期六
// 3. 用字符串赋值
var times=new Date("2019-8-13 13:42");
var times=new Date("2019/02/19");
var times=new Date("Feb 19 2018");
var times=new Date("Monday February 25 2015");
//用字符串赋值,返回时间和设置一样;用数字赋值,返回月份+1。
// 4. 用set赋值
var time=new Date();
time.setFullYear(2019);
time.setMonth(8); //结果:9,返回结果+1
time.setDate(16);
time.setHours(13);
time.setMinutes(42);
time.setSeconds(33);
time.setMilliseconds(67);
3. 获取时间
var time=new Date();
time.getFullYear();
time.getMonth(); //返回结果-1
time.getDate();
time.getHours();
time.getMinutes();
time.getSeconds();
time.getMilliseconds();
time.getTime(); //当前时间到1970年0点的总毫秒数
time.getYear(); //当前时间到1900年的总年数差
4. 日期对象转换成字符串
time.toString();
time.toLocaleString();
time.toLocaleTimeString();
time.toLocaleDateString();
time.toDateString();
time.toTimeString();
time.toUTCString();
二、Math 对象
Math对象不需要实例化 ,直接使用
方法 | 含义 |
---|---|
Math. PI | 圆周率 |
Math. abs ( x) | 绝对值 |
Math. sqrt (4) | 平方根 |
Math. pow ( x, y) | x 的 y 次幂 |
Math. floor (4.5) | 向下取整 |
Math. ceil (3.5) | 向上取整 |
Math. round (3.2) | 四舍五入 |
Math. random () | 随机数 0~1 |
Math. max ( 2,4,8) | 最大值 |
Math. min ( 2,4,8) | 最小值 |
Math. sin ( 1) | 正弦 |