JavaScript 的内置对象
- 1、JavaScript 的对象分类
- 内置对象都是由ES组织提供,如String,Array,Number……
- 外部对象分为 windows(BOM) 和 document(DOM)
- 自定义对象,如自定义的function
- 2、RegExp 对象 (正则表达式)
- 1、创建RegExp对象
- 语法:ver reg = / 正则表达式 / 修饰符;
- var reg = new RegExp(“正则表达式”,“修饰符”);
- 例如:var reg = / abc /g; 全局匹配字符串abc
- var reg = / \d{6}/g; 匹配6位数字
- 2、RegExp对象的方法
函数 | 说明 |
---|
reg.test(string) | 如果string合格reg格式的话,返回true(string:要验证的字符串) |
var reg = /^\d{3}$/g;
var input = prompt("输入3位数字");
if (reg.test(input)){
alert("输入正确");
}else{
alert("输入错误");
}
属性 | 说明 |
---|
Math.PI | 圆周率 (3.141592653589793) |
Math.E | 自然对数的底数 (2.718281828459045) |
函数 | 说明 |
---|
Math.sin(x)/Math.cos(x)…… | 三角函数 |
Math.sqrt(x,y) | x 开 y 次方 |
Math.log(x) | 对数 |
Math.pow(x,y) | x 的 y 次方 |
Math.abs(x) | 绝对值 |
Math.max(x,y) | 取最大值 |
Math.min(x,y) | 取最小值 |
Math.random() | 随机生成0—1之间的小数 |
Math.round(x) | 将 x 四舍五入到整数 |
语法 | 说明 |
---|
var now = new Date(); | 获取当前系统时间 |
now = new Date(“2019/01/01”); | 初始化自定义日期时间对象 |
var now = new Date();
console.log(now);
var now = new Date("2019/01/01");
console.log(now);
函数 | 说明 |
---|
getTime() | 读取当前时间的毫秒数,返回从1970年1月1日至 date 的毫秒数 |
setTime(n) | n为毫秒数,该设置的毫秒数是自1970年1月1日对应的时间的日期 |
var date = new Date("2019/01/01");
console.log(date.getTime());
date.setTime(1546272000000);
console.log(date)
函数 | 说明 |
---|
getFullYear() | 获取日期时间对象的年份 |
getYear() | 获取自1900年以来到当前时间的年份 |
getMonth() | 获取时间对应的月份,返回0-11的数,0表示1月,11表示12月 |
getDate() | 获取时间对应的日号,返回1-31的数,1表示1号 |
getDay() | 获取时间对应的星期数,返回0-6的数,0表示周日,1表示周一 |
getHours() | 获取小时 |
getMinutes() | 获取分钟 |
getSeconds() | 获取秒 |
getMilliseconds() | 获取毫秒 |
toString() | 装换为字符串 |
toLocaleString() | 将当前时区转换为字符串 |
toLocaleTimeString() | 将当前时区的时间转换为字符串 |
toLocaleDateString() | 将当前时区的日期转换为字符串 |
var now = new Date();
console.log(now.getFullYear());
console.log(now.getYear());
console.log(now.getMonth());
console.log(now.getDate());
console.log(now.getDay());
console.log(now.getHours());
console.log(now.getMinutes());
console.log(now.getSeconds());
console.log(now.getMilliseconds());
console.log(now.toString());
console.log(now.toLocaleString());
console.log(now.toLocaleTimeString());
console.log(now.toLocaleDateString());