math对象
成员 | 功能 |
PI | 获取圆周率,结果为3.141592653589793 |
abs(x) | 获取x的绝对值,可传入普通数值或是用字符串表示的数值 |
max() | 获取所有参数中的最大值 |
min() | 获取所有参数中的最小值 |
pow(base,exponent) | 获取基数(base)的指数(exponent)次幂,即 baseexponent |
sqrt(x) | 获取x的平方根 |
ceil(x) | 获取大于或等于x的最小整数,即向上取整(舍弃小数部分,整数部分加 1) |
floor(x) | 获取小于或等于x的最大整数,即向下取整(舍弃小数部分,整数部分不变) |
round(x) | 获取x的四舍五入后的整数值 |
random() | 获取大于或等于0.0且小于1.0的随机值 |
案例:
1)要求:求10-20(包含10和20)之间的随机整数
function getRandom(min,max){
Math.random()
Math.random()*(max-min+1)+min
Math.floor([10,21))
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(getRandom(10,20))
2)利用随机数,实现在数组中随机获取一个元素
function getRandom(min,max){
Math.floor
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(getRandom(10,20))
var arr=['apple','banana','orange','pear']
console.log(arr[getRandom(0,arr.length-1)])
3)要求:随机生成颜色RGB(0-255,0-255,0-255)
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
function getRGB(min,max){
var c1=getRandom(min,max);
var c2=getRandom(min,max);
var c3=getRandom(min,max);
return 'rgb('+c1+','+c2+','+c3+');
}
console.log(getRGB(0,255));
日期对象
语法:
方式1 . 获取当前时间 :
var date1=newDate();
console.log(date1)
输出:WedApr05202320:57:12GMT+0800(中国标准时间)
方式2 . 传入年、月、日、时、分、秒(月的范围是0~11,即真实月份-1):
var date2=newDate(2023,03,06,10,57,56);
console.log(date2)
输出:ThuApr06202310:57:56GMT+0800(中国标准时间)
方式3 . 用字符串表示日期和时间 :
vard ate3=newDate('2023-04-0610:57:56');
console.log(date3)
输出:ThuApr06202310:57:56GMT+0800(中国标准时间)
案例
2023年4月5日星期三请写出这个格式:
function getMyDate(){
var arr=['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
vardate=newDate();
console.log(date);
var str=date.getFullYear()+'年'(date.getMonth()+1)+'月'+date.getDate()+'日'+arr[date.getDay()];
return str;
}
console.log(getMyDate());