js内置对象 Math,Date

内置对象Math,Date

Math对象

console.log(typeof Math);//Math为object类型
  • 圆周率 (Math.PI)
console.log(Math.PI)
console.log(typeof Math.PI)://数据类型为number
  • 随机数 (Math.random())
    • 生成0-1之间的随机数,若想保留小数,可用toFixed(n)保留n位小数
//Math.round(Math.random()*(max-min)+min) 生成min-max以内的随机数
//5-10以内的随机数
console.log(Math.round(Math.random()*(10-5)+5));
//封装函数
function random(min, max) {
        return Math.round(Math.random() * (max - min) + min);
    }
var num=random(5,10);
console.log(number)
  • 向下取整 (Math.floor)

  • 向上取整 (Math.ceil )

  • 取整 四舍五入 (Math.round )

  • 绝对值 (Math.abs )

  • 最大值 (Math.max )

  • 最小值 (Math.min )

    console.log(Math.floor(3.9));//3
    console.log(Math.ceil(3.9));//4
    console.log(Math.round(6.4));//6
    console.log(Math.round(6.5));//7
    console.log(Math.abs(-3));//3
    var arr = [2, 3, 4, 5, 4, 3, 5, 8];
    console.log(Math.max(1, 2, 3, 4, 5));//5
    console.log(Math.max(...arr)); //8
    console.log(Math.min(1, 2, 3, 4, 5));//1
    console.log(Math.min(...arr));//2
    

Data对象

//基于1970年1月1日起
	var date=new Date();
	console.log(date);
	//获取毫秒数
	console.log(date.getTime())
	console.log(date.valueOf())
	//获取年份
	console.log(date.getFullYear());
	//月份
	console.log(date.getMonth()+1)//月份从0-11,得到的月份比实际月份小1,所以需要加一
	//日期
	console.log(date.getDate())
	//星期
	console.log(date.getDay())
	//获取小时
	console.log(date.getHours())
	//分钟
	console.log(date.getMinutes())
	//秒
	console.log(date.getSeconds())
	
//输出时间格式2024/06/01
/* 
var date=new Date()
	function nowtimes(){
		var year=date.getFullYear();
		var month=date.getMonth();
		var day=date.getDay();
		return `${year}/${month}/${day}`
	}
	console.log(nowtimes())//2024/6/1
 */
	var nowdate=new Date()
	function addzero(num){
		return num<10?'0'+num:num;
	}
	
	function nowtimes(){
		var year=nowdate.getFullYear();
		var month=addzero(nowdate.getMonth())
		var day=addzero(nowdate.getDate())
		return `${year}/${month}/${day}`
}
console.log(nowtimes())	
	
  • 字符串补齐padStrat(所需长度,补齐的内容),padEnd(长度,所需的内容)
	var str='1';//字符串格式
	//padStart 往前补数
	console.log(str.padStart(3,'0'))//001
	//padEnd 往后补数
	console.log(str.padEnd(3,'0'))//100

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值